通过重新加载另一个函数来腌制它

问题描述 投票:0回答:1

假设我有以下简单的类:

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进行酸洗,而是使用原始功能(尽管在取消酸洗后,默认情况下它将引用包装的函数)。

有什么建议吗?谢谢!

python python-3.x pickle python-multiprocessing metaclass
1个回答
0
投票

查看源代码,您可以通过ForkingPickler-属性的multiprocessing方法看到Pickler__func__的自定义__name__)的泡菜。因此,我要做的是将wrapper.__name__设置为与原始成员的名称相同:

© www.soinside.com 2019 - 2024. All rights reserved.