本文介绍了如何在python中腌制动态创建的嵌套类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套类:


class WidgetType(object):

    class FloatType(object):
        pass

    class TextType(object):
        pass

..和引用嵌套类类型的对象(不是它的实例)

.. and an object that refers the nested class type (not an instance of it) like this


class ObjectToPickle(object):
     def __init__(self):
         self.type = WidgetType.TextType

尝试序列化ObjectToPickle类的实例会导致:

Trying to serialize an instance of the ObjectToPickle class results in:

有没有办法在python中腌制嵌套类?

Is there a way to pickle nested classes in python?

推荐答案

pickle模块正在尝试获取TextType类。来自模块。但是由于该类是嵌套类,因此无法正常工作。 jasonjs的建议会起作用。
以下是在pickle.py中负责错误消息的行:

The pickle module is trying to get the TextType class from the module. But since the class is nested it doesn't work. jasonjs's suggestion will work.Here are the lines in pickle.py responsible for the error message:

    try:
        __import__(module)
        mod = sys.modules[module]
        klass = getattr(mod, name)
    except (ImportError, KeyError, AttributeError):
        raise PicklingError(
            "Can't pickle %r: it's not found as %s.%s" %
            (obj, module, name))

klass = getattr(mod,name)当然不适用于嵌套类。为了演示正在发生的情况,请在对实例进行酸洗之前尝试添加以下行:

klass = getattr(mod, name) will not work in the nested class case of course. To demonstrate what is going on try to add these lines before pickling the instance:

import sys
setattr(sys.modules[__name__], 'TextType', WidgetType.TextType)

此代码将TextType作为属性添加到模块。酸洗应该很好。不过,我不建议您使用此技巧。

This code adds TextType as an attribute to the module. The pickling should work just fine. I don't advice you to use this hack though.

这篇关于如何在python中腌制动态创建的嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:41
查看更多