反射就是通过字符串的形式导入模块,并寻找指定函数执行; 如下4个内置函数
- getattr(object,attr[,default])
获取指定字符串的对象属性或者方法,有属性则返回属性值,由方法则返回方法的内存地址 - hasattr(object,attr)
判断字符串名称的对象是否由该属性或方法,返回True或False - setattr(boject,attr,value)
为指定字符串名称的对象设置属性,如果对象已有该属性则覆盖该属性值,没有该属性则新增该属性赋值 - delattr(object,attr)
删除指定字符串名称的对象某属性,没有该属性会报错 示例:
class MyReflection:
name = "KDTtest"
def __init__(self):
print("类构造方法")
def add(self,a,b):
print(a+b)
def test(self):
return [11,22,33,44]
if __name__ == '__main__':
ref = MyReflection()
ref.add(10,20)
eval("ref.add(4,56)")
getattr(ref,"add")(4,5)
print(getattr(ref,"name"))
list = getattr(ref,"test")()
print(list)
print(hasattr(ref,"nnn"))
print(hasattr(ref,"test"))
setattr(ref,"name","类反射setattr()")
print(ref.name)
delattr(ref,"name")
print(ref.name)
"""
进阶:对模块、类进行基于字符串的调用和实例化
"""
module = __import__("reflection")
myclass = getattr(module,"MyReflection")
clsname = myclass()
mylist = getattr(clsname,"test")()
print(mylist)
|