Python 如何将类装饰器与pickle一起使用?

Python 如何将类装饰器与pickle一起使用?,python,class,decorator,pickle,Python,Class,Decorator,Pickle,我想使用类装饰器(不是函数装饰器!),例如 并且能够对对象进行酸洗: import pickle a = cls() a.run() s = pickle.dumps(a) 但是,pickle返回一个错误: PicklingError: Can't pickle <class '__main__.new_cls'>: it's not found as __main__.new_cls PicklingError:无法pickle:找不到它作为\uuuu main\uuuuu.

我想使用类装饰器(不是函数装饰器!),例如

并且能够对对象进行酸洗:

import pickle

a = cls()
a.run()
s = pickle.dumps(a)
但是,pickle返回一个错误:

PicklingError: Can't pickle <class '__main__.new_cls'>: it's not found as __main__.new_cls
PicklingError:无法pickle:找不到它作为\uuuu main\uuuuu.new\u cls
任何帮助都将不胜感激

在对类进行pickle时。如果
class\u decorator
返回的新类的名称未在 在模块的顶层,则会出现以下错误:

PicklingError: Can't pickle <class '__main__.new_cls'>: it's not found as __main__.new_cls 
然后,代码将正常运行:

import pickle

def class_decorator(cls):
    class new_cls(cls):
        def run(self, *args, **kwargs):
            print 'In decorator'
            super(new_cls,self).run(*args, **kwargs)
    new_cls.__name__ = cls.__name__
    return new_cls

@class_decorator
class cls(object):
    def run(self):
        print 'called'

a = cls()
print(a)
# <__main__.cls object at 0x7f57d3743650>

a.run()
# In decorator
# called

s = pickle.dumps(a)
# Note "cls" in the `repr(s)` below refers to the name of the class. This is
# what `pickle.loads` is using to unpickle the string
print(repr(s))
# 'ccopy_reg\n_reconstructor\np0\n(c__main__\ncls\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n.'

b = pickle.loads(s)
print(b)
# <__main__.cls object at 0x7f57d3743690>

b.run()
# In decorator
# called
导入pickle
def class_装饰器(cls):
新类别cls(cls):
def运行(自身、*args、**kwargs):
打印“在装饰器中”
超级(新cls,自我)。运行(*args,**kwargs)
新建\u cls.\u\u名称\u\u=cls.\u\u名称__
返回新的\u cls
@高级装饰师
类别cls(对象):
def运行(自):
打印“调用”
a=cls()
印刷品(a)
# 
a、 运行()
#室内装饰
#叫
s=酸洗。转储(a)
#注:下面“repr(s)”中的“cls”指的是类的名称。这是
#“pickle.loads”用来解开字符串的是什么
印刷品(报告)
#“ccopy\u reg\n\u重建器\np0\n(c\uuuuu main\uuuuuncls\np1\nc\uuuuuuu内置\uuuuuuu\nobject\np2\nNtp3\nRp4\n.”
b=酸洗负荷
印刷品(b)
# 
b、 运行()
#室内装饰
#叫

这在Python2中运行良好,但在Python3中似乎失败:
AttributeError:无法pickle本地对象“class\u decorator..new\u cls”
此处相同:在Python3.8中不起作用
new_cls.__name__ = cls.__name__
import pickle

def class_decorator(cls):
    class new_cls(cls):
        def run(self, *args, **kwargs):
            print 'In decorator'
            super(new_cls,self).run(*args, **kwargs)
    new_cls.__name__ = cls.__name__
    return new_cls

@class_decorator
class cls(object):
    def run(self):
        print 'called'

a = cls()
print(a)
# <__main__.cls object at 0x7f57d3743650>

a.run()
# In decorator
# called

s = pickle.dumps(a)
# Note "cls" in the `repr(s)` below refers to the name of the class. This is
# what `pickle.loads` is using to unpickle the string
print(repr(s))
# 'ccopy_reg\n_reconstructor\np0\n(c__main__\ncls\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n.'

b = pickle.loads(s)
print(b)
# <__main__.cls object at 0x7f57d3743690>

b.run()
# In decorator
# called