相关疑难解决方法(0)

泡菜和装饰类(PicklingError:不同的对象)

下面的最小示例使用一个虚拟装饰器,该装饰器在构造装饰类的对象时仅打印一些消息。

import pickle


def decorate(message):
    def call_decorator(func):
        def wrapper(*args, **kwargs):
            print(message)
            return func(*args, **kwargs)

        return wrapper

    return call_decorator


@decorate('hi')
class Foo:
    pass


foo = Foo()
dump = pickle.dumps(foo) # Fails already here.
foo = pickle.loads(dump)
Run Code Online (Sandbox Code Playgroud)

但是,使用它会pickle引发以下异常:

_pickle.PicklingError: Can't pickle <class '__main__.Foo'>: it's not the same object as __main__.Foo
Run Code Online (Sandbox Code Playgroud)

有什么我可以解决的吗?

python decorator pickle python-3.x python-decorators

2
推荐指数
1
解决办法
1022
查看次数