The role of reflection in a Python class

Source: Internet
Author: User

#Coding:utf-8" "#反射的基本用法: Hasattr Determines whether a method exists in the instance getattr specifies a method name, gets the memory address of the method, adds "()" parentheses and executes" "ImportSYSclassWebServer (object):def __init__(self,host,port): Self.host=host Self.port=PortdefStart (self):Print("Server is starting ...")    defStop (self):Print("Server is stopping")    defRestart (self): Self.stop () Self.start ()#Example: Get the first content of a user input, call the appropriate methodif __name__=="__main__":    #sys.argv[1] means: Receives the first parameter entered by the user    #method One: This method can be implemented, but very low (), do not recommend the use of    #Server = WebServer ("127.0.0.1", 3306)    #cmd_server = {"Start": Server.start, "Stop": server.stop, "restart": Server.restart}    #if sys.argv[1] in Cmd_server:    #Cmd_server[sys.argv[1]] ()    ##方法二: But this method has a problem, how to call the user input string name corresponding method?     #cmd_server = sys.argv[1]    #if cmd_server in webserver.__dict__:    #print (cmd_server)    #WebServer ("127.0.0.1", 3306). Cmd_server #cmd_server为用户输入的字符串名字, but that's obviously not a good call.    #method Three: Use the Hasattr and GetAttr methods to determine if the method exists in the object and get the memory address of the method in the objectServer = WebServer ("127.0.0.1", 3306)    ifHasattr (Server,sys.argv[1]):#hasattr: Determines whether a class contains a method or propertyFunc = GetAttr (server,sys.argv[1])#getattr; get Server.start memory addressfunc ()
" "SetAttr binds a function to an instance description: How do you bind a function outside a class to an instance? " "ImportSYSclassWebServer (object):def __init__(self,host,port): Self.host=host Self.port=PortdefStart (self):Print("Server is starting ...")    defStop (self):Print("Server is stopping")    defRestart (self): Self.stop () Self.start ()#How do I bind this function to an instance? defRun_server (obj,name):Print("runing is%s"%Obj.restart (), name)if __name__=="__main__": Server= WebServer ("localhost", 3306) setattr (server,'Run', Run_server)#The Test_run function is bound to the server instance by the SetAttr method, which is called "Run" .Server.run (Server,"Apache")
" "Delattr Delete An instance or a method in a class" "ImportSYSclassWebServer (object):def __init__(self,host,port): Self.host=host Self.port=PortdefStart (self):Print("Server is starting ...")    defStop (self):Print("Server is stopping")    defRestart (self): Self.stop () Self.start ()defrun_server (name):Print("runing is%s", name)if __name__=="__main__": Server= WebServer ("localhost", 3306) setattr (server,'Run', Run_server) delattr (WebServer,"Start")#Delete a method inside a classDelattr (Server,"Host")#Delete An instance's propertiesDelattr (Server,'Run')#Remove properties added to an instance via SetAttr    Print(server.__dict__, WebServer.__dict__)#View

The role of reflection in a Python class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.