您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

腌制一个类时,将 __腌制该类 名称@L_404_3@。如果class_decorator返回一个 名称 未在模块顶层定义的新类,则会出现错误

PicklingError: Can't pickle <class '__main__.new_cls'>: it's not found as __main__.new_cls

您可以通过将新修饰的类命名为未修饰的类来避免该错误

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
其他 2022/1/1 18:40:07 有456人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶