假设我有以下简单的类:
class HelloWorld:
def call(self):
print('Hello World!')
然后我可以将HelloWorld.call
用于多处理,尽管python知道如何腌制HelloWorld.call
。但是,说我想将该函数包装在元类中,
class MetaClass(type):
def __new__(mcs, name, bases, dct):
def wrap(f):
def wrapper(self):
print(f.__qualname__)
f(self)
return wrapper
new_dct = dict()
for attr_name in dct.keys():
if callable(dct[attr_name]):
new_dct[attr_name] = wrap(dct[attr_name])
else:
new_dct[attr_name] = dct[attr_name]
return type.__new__(mcs, name, bases, new_dct)
class HelloWorld(metaclass=MetaClass):
def call(self):
print('Hello World!')
然后,我不能将HelloWorld.call
用于多处理,因为它不会腌制。我想要的是使python不使用wrapper-function进行酸洗,而是使用原始功能(尽管在取消酸洗后,默认情况下它将引用包装的函数)。
有什么建议吗?谢谢!
查看源代码,您可以通过ForkingPickler
-属性的multiprocessing
方法看到Pickler
(__func__
的自定义__name__
)的泡菜。因此,我要做的是将wrapper.__name__
设置为与原始成员的名称相同: