---- reflection self-reflection of the program

First, the concept of reflection

Smith is the first time in 1982, mainly refers to the program can access, the ability to detect and modify its own state or behavior (introspection).

It puts forward the concept quickly led to research on the application of computer science reflective. It was first adopted design of programming languages,

And it has made achievements in Lisp and object-oriented aspects.

Second, the four function can be achieved introspective

① hasattr (object, "attribute name")

Analyzing there is no object to obtain a character string corresponding to a property or method, return True or False

② getattr (object, "attribute name")

Direct property or method to get the name of the memory address, will not be found error

Can be added to the default parameters, you can not find the default argument is returned

③ setattr (object, "attribute name", "attribute value")  

Set attributes, data attributes can be set, function attribute may be provided

④ delattr (object, "attribute name")

BlackMedium class: 
    feture = "Ugly" 
    DEF the __init __ (Self, name, addr): 
        the self.name name = 
        self.addr addr = 

    DEF sell_hourse (Self): 
        Print ( "{} are selling the house" .format (self.name) ) 

    DEF rent_hourse (Self): 
        Print ( "{} is rent" .format (the self.name)) 

B1 = BlackMedium ( 'opposite to Wan,' the 'home garden') 

Print (the hasattr (B1, "name") ) 
Print (getattr (B1, "sell_hourse")) 
S = getattr (B1, "sell_hourse") () run # which 
print (getattr (b1, "aaaa ", " do not have this property oh"))

Example ③ and ④:

BlackMedium class: 
    feture = "Ugly" 
    DEF the __init __ (Self, name, addr): 
        the self.name name = 
        self.addr addr = 

    DEF sell_hourse (Self): 
        Print ( "{} are selling the house" .format (self.name) ) 

    DEF rent_hourse (Self): 
        Print ( "{} is rent" .format (the self.name)) 

B1 = BlackMedium ( 'opposite to Wan,' the 'home garden') 
setattr (B1, "Jinling", "mygirlfriends ") # add properties equivalent to = b1.jinling" mygirlfriends " 
Print (B1 .__ dict__ magic) 
setattr (B1," name "," Liu ") # modify properties 
Print (B1 .__ dict__ magic) 
setattr (B1, 'FUNC', lambda x: x + 1) # set function attributes 
Print (B1 .__ dict__ magic) 
Print (b1.func (. 6)) # call functions provided above 


delattr (b1,"name") # delete the name attribute is equivalent to b1.name del 
Print (b1 .__ dict__)

  

Third, why reflection

The advantage is that reflection can be defined first interface, the interface is only really performed after the completion of this plug and play, this is actually a 'late binding'

That you can advance to the main logic written (only defines interfaces), and then again late realize the function interface

################################

Guess you like

Origin www.cnblogs.com/dabai123/p/11595178.html