如何向 python class 对象添加字典属性?

How to add a dictionary attribute to python class object?

我有一些正在使用的代码 (specifically Parsetron) 是为 Python 2.7 编写的,我正在尝试 运行 使用 python 3.4 毫不奇怪,它会抛出错误。

我特别关注的错误是:

def __new__(cls):
    return cls.__dict__['_grammar_']

KeyError: '_grammar_'

cls是class对象,确实没有键“_grammar_”。我的问题当然是,如何摆脱这个错误以及它出现的原因。在 python 2.7 中,__dict__ 会向 class 对象添加键值,而 Python 3.x 不会吗? 运行 在调试期间通过线程似乎没有在任何地方添加这个值。有人知道怎么回事吗?

看代码可以看到Grammar._grammar_class属性其实是set by the metaclass:

dct["_grammar_"] = GrammarImpl(name, dct)

但是,Grammar uses the 2.x syntax 用于设置 metaclass:

__metaclass__ = MetaGrammar

要针对 Python 3.x 进行调整,请使用 new syntax:

class Grammar(metaclass=MetaGrammar):