python笔记:反射 在python中,可以使用很简单的用内置函数__import__来实现“反射”。参考代码如下: module = __import__("cacl.add", fromlist=True) abs_args_method = getattr(module, 'abs_args') add_method = getattr(module, 'add')当然,还有更简单粗暴的方法:exec('print("haha")')对于类可以这么处理:import types _method = { "say_hello":["test1", "SayHello"] } class Test(object): def __init__(self): self.base_char = "yzh" for key, item in _method.items(): module = __import__(item[0],fromlist=True) module_class = getattr(module, item[1]) class_obj = module_class(self.base_char) self.__dict__[key] = class_obj.do_it test = Test() test.say_hello("ha") 来自 大脸猪 写于 2016-10-27 15:05 -- 更新于2020-10-19 13:06 -- 0 条评论