【发布时间】:2017-05-30 18:25:29
【问题描述】:
我正在编写一个 Python 类来包装/装饰/增强来自名为 petl 的包中的另一个类,该包是 ETL(数据移动)工作流的框架。由于设计限制,我不能只是子类化它;每个方法调用都必须通过我自己的类发送,这样我就可以控制传回的对象类型。所以原则上这是一个代理类,但我在使用现有的答案/食谱时遇到了一些麻烦。这是我的代码的样子:
from functools import partial
class PetlTable(object):
"""not really how we construct petl tables, but for illustrative purposes"""
def hello(name):
print('Hello, {}!'.format(name)
class DatumTable(object):
def __init__(self, petl_tbl):
self.petl_tbl = petl_tbl
def __getattr__(self, name):
"""this returns a partial referencing the child method"""
petl_attr = getattr(self.petl_tbl, name, None)
if petl_attr and callable(petl_attr):
return partial(self.call_petl_method, func=petl_attr)
raise NotImplementedError('Not implemented')
def call_petl_method(self, func, *args, **kwargs):
func(*args, **kwargs)
然后我尝试实例化一个表并调用一些东西:
# create a petl table
pt = PetlTable()
# wrap it with our own class
dt = DatumTable(pt)
# try to run the petl method
dt.hello('world')
这给出了TypeError: call_petl_method() got multiple values for argument 'func'。
这只发生在位置参数上; kwargs 似乎很好。我很确定这与self 没有被传入有关,但我不确定解决方案是什么。谁能想到我做错了什么,或者更好的解决方案?
【问题讨论】: