##. Python's Path to self-study: Reflection (very important programming ideas)

Source: Internet
Author: User

The meaning of reflection: Gets the memory address of a method of a class through a string, and calls the method.

Format: If hasattr(self, ' anattr ')

Func = getattr(self, ' anattr ') #获取内存地址

Func () # calls the method, equivalent to Anattr ()

setattr(x, ' Y ', v     )

     delattr (x, ' Y ')

Look at the following example

version One : Inefficient, if the method in the class webserver more than hundred, then the main function of the IF statement will be judged hundreds of times.

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 ()if __name__=="__main__": Server= WebServer ('localhost', 333)    Print(Sys.argv[1])#the first parameter when executing a script    ifSYS.ARGV[1] = ='Start': Server.start ()elifSYS.ARGV[1] = ='Stop': Server.stop ()elifSYS.ARGV[1] = ='Restart': Server.restart ()

version Two : the idea of introducing a dictionary, but there is the phenomenon of code reuse, you can continue to improve

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 ()if __name__=="__main__": Server= WebServer ('localhost', 333)    Print(sys.argv[1]) Cmd_dic= {        'Start': Server.start,'Stop': Server.stop,}ifSYS.ARGV[1]inchcmd_dic:cmd_dic[sys.argv[1]] ()

version Three : Introducing Reflection

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 ()if __name__=="__main__": Server= WebServer ('localhost', 333)    Print(sys.argv[1])    ifHasattr (server, sys.argv[1]): Func= GetAttr (server, sys.argv[1])#Gets the memory address of the Server.startFunc ()#equivalent to Server.start ()

The SetAttr of Reflection method

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 ()defTestRun (INS, name):#This method is not a method of class, but it can be bound to an instance using set    Print("running ....", Name,ins.host)#ins equals selfif __name__=="__main__": Server= WebServer ('localhost', 333) Server1= WebServer ('Localhost1', 666)    Print(sys.argv[1])    #setattr (x, ' Y ', V) is equivalent to x.y = vSetAttr (Server,'Run', TestRun)#TestRun is bound to instance server and renamed to runServer.run (Server,'Wuwen')#Passing server to INS (instance)Server1.run (Server,'Wuwen')

The Delattr of Reflection method

classWebServer (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 ()if __name__=="__main__": Server= WebServer ('localhost', 333) delattr (server,'Stop')#error notation, instance cannot method in parameter class    Print(server.host) delattr (server,'Host')#删除property in the argument instance host    Print(server.host) delattr (WebServer,'Restart')#删除The restart method in the parameter class    Print(Server.restart ())

##. Python's Path to self-study: Reflection (very important programming ideas)

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.