【问题标题】:How to add a dictionary attribute to python class object?如何将字典属性添加到 python 类对象?
【发布时间】:2015-11-10 16:43:56
【问题描述】:

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

我特别关注的错误是:

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

KeyError: '_grammar_'

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

【问题讨论】:

标签: python python-2.7 python-3.x nlp


【解决方案1】:

查看代码可以看到Grammar._grammar_类属性其实是set by the metaclass

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

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

__metaclass__ = MetaGrammar

要使其适用于 Python 3.x,请使用 new syntax

class Grammar(metaclass=MetaGrammar):

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2021-10-26
    • 2013-12-08
    • 2021-03-15
    • 2015-11-15
    相关资源
    最近更新 更多