python3中反射的基本方法有哪些

这篇文章主要介绍了python3中反射的基本方法有哪些,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

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

1.getattr()方法

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

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)
输出结果就是True

4.delattr()方法

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

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

感谢你能够认真阅读完这篇文章,希望小编分享的“python3中反射的基本方法有哪些”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注行业资讯频道,更多相关知识等着你来学习!