【发布时间】:2018-12-27 21:22:29
【问题描述】:
我在某个路径中有一个模块。我想创建一个与模块具有相同属性的类(以便可以与模块相同的方式使用它)但在访问属性之前执行一些自定义操作 - 例如重新加载模块。
def get_method_with_extra(method_name, module):
def method_with_extra(self, *args):
imp.reload(module)
func_to_call = getattr(module, method_name)
func_to_call(*args)
return method_with_extra
class tester():
def __init__(self, module_path):
self.module = imp.load_source('module', module_path)
method_list = [func for func in dir(self.module) if
callable(getattr(self.module, func))]
for method_name in method_list:
method_with_extra = get_method_with_extra(method_name,
self.module)
setattr(type(self), method_name, method_with_extra)
因此,例如,如果模块有一个名为“Parse”的方法,我希望测试器的实例 - tess - 也有它,并且我能够调用 tess.parse() 来重新加载内部模块,然后调用模块的 parse()。相反,我收到此错误:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<string>", line 4, in __init__
AttributeError: attribute '__call__' of 'namespace#' object is read-only
【问题讨论】: