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))

#5. 反射可以简化代码:
class Goods:
    def __init__(self,name,price):
        self.name = name
        self.price = price
g = Goods('apple',8)
属性名 = input('请输入要查找的内容:')
if 属性名 == 'name':
    ret = getattr(g,属性名)
    print(ret)
elif 属性名 == 'price':
    ret = getattr(g,属性名)
    print(ret)
else:
    print('没找到此内容')

class Goods:
    def __init__(self,name,price):
        self.name = name
        self.price = price
g = Goods('apple',8)
属性名 = input('请输入要查找的内容:') #请输入要查找的内容:name
ret = getattr(g,属性名)
print(ret)#apple
复制代码

 

posted @   梁劲雄  阅读(140)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
阅读排行:
· 几个技巧,教你去除文章的 AI 味!
· 对象命名为何需要避免'-er'和'-or'后缀
· 系统高可用的 10 条军规
· 关于普通程序员该如何参与AI学习的三个建议以及自己的实践
· AI与.NET技术实操系列(八):使用Catalyst进行自然语言处理
点击右上角即可分享
微信分享提示