day17- reflection

# Reflected two most commonly used methods: the hasattr getattr 
# 1. reflecting object attributes reflecting object methods: 
class Goods:
     DEF  the __init__ (Self, name): 
        the self.name = name
     DEF . Price (Self):
         Print ( ' {} of 8 yuan price is ' .format (the self.name)) 
Apple = Goods ( ' Apple ' ) 
RET = getattr (Apple, ' name ' ) # attribute string using writing. Reflecting object properties. 
Print (RET)   # Apple, printing attribute value 
RET1 = getattr (Apple, ' . price ') # Methods are also used to write a string. The method of reflecting object. 
RET1 ()      # Apple price of $ 8, the method call 

# 2. the hasattr 
class Goods:
     DEF  the __init__ (Self, name): 
        the self.name = name 
G = Goods ( ' Apple ' )
 IF the hasattr (G, ' name ' ) : # If the object has a name attribute 
    RET = getattr (G, ' name ' ) # reflection (acquired) object properties 
    Print (RET) # Apple 

# 3. reflection class attributes, methods reflection class: 
class Goods:
    Discount = 0.8 
    @classmethod 
    DEF . price (CLS):
         Print ( ' apple price is $ 10 ' ) 
RET1 = getattr (Goods, ' Discount ' )
 Print (RET1) 
RET = getattr (Goods, ' . price ' ) 
RET () 

# 4. properties reflection module, the module method 
Import Model 
RET = getattr (Model, ' name ' )
 Print (RET) # Apple 
RET1 = getattr (Model, ' . price ' ) 
RET1 () # Apple's price is 8 yuan 
# the model.py code is: 
# name = 'Apple' 
# DEF. price (): 
#     Print ( '{} is the price of 8 yuan' .format (name))

 

Guess you like

Origin www.cnblogs.com/python-daxiong/p/11235630.html