成都创新互联网站制作重庆分公司

python学习:反射的四种基本方法

class Person(object):
    
    def __init__(self):
        pass
    def info(self):
        print('我是person类中的info方法')

1.getattr()方法

这个方法是根据字符串去某个模块中寻找方法

创新互联建站主营崇阳网站建设的网络公司,主营网站建设方案,手机APP定制开发,崇阳h5微信小程序开发搭建,崇阳网站营销推广欢迎崇阳等地区企业咨询

instantiation = reflect.Person()#先实例化
f = getattr(instantiation,'info')#使用getattr函数去寻找字符串的同名方法
f()#调用方法
#输出结果:我是person类中的info方法

2.hasattr()方法

这个方法是根据字符串去判断某个模块中该方法是否存在

instantiation = reflect.Person()#先实例化
f = hasattr(instantiation,'info')
print(f)
#输出结果:True

3.setattr()方法

这个方法是根据字符串去某个模块中设置方法

instantiation = reflect.Person()
f = setattr(instantiation,'exit','this is a exit method')
f2 = hasattr(instantiation,'exit')
print(f2)
#python学习交流群:
#输出结果就是True

4.delattr()方法

这个方法是根据字符串去某个模块中删除方法

instantiation = reflect.Person()#实例化
f = delattr(instantiation,'exit')
f = hasattr(instantiation,'exit')
print(f)
#输出结果就是False

文章题目:python学习:反射的四种基本方法
当前地址:http://cxhlcq.com/article/dsogcjs.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部