python - 反射
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())
疯狂的妞妞 :每一天,做什么都好,不要什么都不做!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY