python中的反射
反射
- 原理:在python中万物皆对象,对象中的所有的属性和方法都是通过字典形式保存的,如果我们想获得对象中的某个属性或方法只需要:
- 首先获得该对象的所有属性和函数的字典
- 通过键key的索引获取相应的值
class A:
def __init_(self, name):
self.name = name
def func(self):
pass
a = A('a)
setattr(a, 'age', 10)
getattr(a, 'sex', '没有找到')
hasattr(a, 'age')
delattr(a, 'age')
msg = input('please enter a method name:')
if hasattr(a, msg):
getattr(a, msg)()
else:
print('not find')
getattr(a, msg, 'not find')
def fun():
pass
def foo():
pass
methodName = input('please enter method name:')
import sys
obj = sys.__modules__['__main__]
if hasattr(obj, methodName):
getattr(obj, methodName)
else:
print('not find')
globals()[methodName]()