反射
准确理解:
根据字符串的形式去模块中寻找元素
粗鲁理解:
通过字符串的形式导入模块
通过字符串的形式,去模块中寻找指定函数,并执行
#通过输入导入模块、函数 r = input("请输入导入模块:") p_func = input("请输入要导入的函数:") dd = __import__(r) #导入模块 new_func = getattr(dd, p_func) #d导入函数 t_func = hasattr(dd, p_func) #判断模块元素是否存在 a_func= setattr(dd, "name", "123") #在模块中增加元素 (源文件不会改变) print(hasattr(dd, "name")) d_func = delattr(dd, "name") #删除模块元素 print(hasattr(dd, "name")) print(t_func) t = new_func(1 , 3) print(t)
class Foo: def __init__(self, name): self.name = name def show(self): print("show") #反射,类只能找类的成员 r = hasattr(Foo, "show") print(r) #反射,对象可以找对象、类的成员 obj = Foo("alex") p = hasattr(obj, "name") print(p)