网络编程
位置:首页>> 网络编程>> Python编程>> python3 反射的四种基本方法解析

python3 反射的四种基本方法解析

作者:小张的博客  发布时间:2023-10-25 16:04:39 

标签:python,3,反射,方法

这篇文章主要介绍了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

来源:https://www.cnblogs.com/Zhang-engineer/p/11160554.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com