Python namedtuple: AttributeError: 'tuple' object has no attribute 'end_pos'

Python namedtuple: AttributeError: 'tuple' object has no attribute 'end_pos'

我有一个 class 开头如下:

from collections import namedtuple

class Parser:
    Rule = namedtuple('Rule', ['lhs', 'rhs', 'dot_pos', 'start_pos', 'end_pos'])

    # __init__ ...

由于 PyCharm 通过给我适当的建议正确地检测到我所有的元组元素命名,我认为到目前为止我做的是正确的,创建了一些 Rule class上面显示的语法。

现在,我的 Parser class 中有一个方法需要一个 Rule 参数:

def add(self, dot_rule: Rule):
    print(dot_rule.end_pos)
    # ...

不幸的是,当我尝试调用 dot_rule 的一个元素时,就会出现以下错误,例如 end_pos:

AttributeError: 'tuple' object has no attribute 'end_pos'

我在使用namedtuple时误解了什么?

编辑: 我按以下方式调用方法 add,其中 lhsrhspos 是一些预先计算的值:

self.add((lhs, rhs, 0, pos, pos))

我想既然 namedtuple 据说与 tuple 向后兼容,这就是正确的语法。显然,该参数现在被视为普通的 tuple 而不是 Rule。我在这里可以做什么不同的事情?

编辑 2: 回溯消息:

Traceback (most recent call last):
  File "...\earley.py", line 19, in <module>
    main()
  File "...\earley.py", line 14, in main
    parser = Parser(grammar, lexicon, sentence)
  File "...\parser.py", line 21, in __init__
    self.parse(sentence)
  File "...\parser.py", line 56, in parse
    self.predict('S', i)
  File "...\parser.py", line 41, in predict
    self.add((lhs, rhs, 0, pos, pos))  # (X -> .α, i, i)
  File "...\parser.py", line 24, in add
    print(dot_rule.end_pos)
AttributeError: 'tuple' object has no attribute 'end_pos'

你可以试试这个:本质上你传递给它的是一个 class 元组而不是 namedtuple 调用规则。参见:

而不是 self.add((lhs, rhs, 0, pos, pos))

使用self.add(Parser.Rule(lhs, rhs, 0, pos, pos))