import types
import logger_factory
import typing
# 从 import 的对象中,直接获取属性
logger = getattr(logger_factory, "logger")
print(logger)
# 通过 class 创建对象
class MyClass:
def __init__(self):
self.value = None
def getValue(self):
return self.value
def setValue(self, value):
self.value = value
# 获取对象的 Class
clazz = getattr(MyClass(), '__class__')
# true - true - false
print(isinstance(clazz, typing.Callable))
print(isinstance(clazz, type))
print(isinstance(clazz, types.MethodType))
# 创建类的实例
instance = clazz()
# 获取 setter 函数
method = getattr(instance, "setValue")
method(10)
# true - false - true
print(isinstance(method, typing.Callable))
print(isinstance(method, type))
print(isinstance(method, types.MethodType))
# typing 和 types 中没找到 Class 对应的类型
# type 是所有 object 的元类,所有对象直接或间接继承自 type
# 获取 getter 函数
method = getattr(instance, "getValue")
ret = method()
print(ret)
# 获取 getter 函数
value = getattr(instance, "value")
print(type(value))
# 判断是否包含名称叫 name 的属性
print(hasattr(instance, 'value'))
# 设置属性值
setattr(instance, 'value', 20)
print(method())
标签:反射,python,self,value,instance,print,isinstance,method
From: https://www.cnblogs.com/chenss15060100790/p/18581354