day17-反射

#反射最常用的两个方法:hasattr getattr
# 1. 反射对象属性,反射对象方法:
class Goods:
    def __init__(self,name):
        self.name = name
    def price(self):
        print('{}的价格是8元'.format(self.name))
apple = Goods('apple')
ret = getattr(apple,'name') #属性使用字符串的形式书写。反射对象属性。
print(ret)  #apple ,打印属性值
ret1 = getattr(apple,'price') #方法也是使用字符串的形式书写。反射对象的方法。
ret1()     #apple的价格是8元 ,方法调用

# 2. hasattr
class Goods:
    def __init__(self,name):
        self.name = name
g = Goods('apple')
if hasattr(g,'name'): #如果对象有name属性
    ret = getattr(g,'name') #反射(获取)对象属性
    print(ret) #apple

# 3. 反射类属性,反射类方法:
class Goods:
    discount = 0.8
    @classmethod
    def price(cls):
        print('苹果的价格是10元')
ret1 = getattr(Goods,'discount')
print(ret1)
ret = getattr(Goods,'price')
ret()

# 4. 反射模块属性,模块方法
import model
ret = getattr(model,'name')
print(ret) #apple
ret1 = getattr(model,'price')
ret1() #apple的价格是8元
#model.py的代码是:
# name = 'apple'
#def price():
#    print('{}的价格是8元'.format(name))

猜你喜欢

转载自www.cnblogs.com/python-daxiong/p/11235630.html
今日推荐