[英]Python namedtuple: AttributeError: 'tuple' object has no attribute 'end_pos'
I have a class that starts as follows:我有一堂课,开头如下:
from collections import namedtuple
class Parser:
Rule = namedtuple('Rule', ['lhs', 'rhs', 'dot_pos', 'start_pos', 'end_pos'])
# __init__ ...
Since PyCharm detected all my tuple element namings correctly by giving me proper suggestions, I assumed I did it the right way so far, creating a little Rule
class with the syntax shown above.由于 PyCharm 通过给我正确的建议正确地检测到了我所有的元组元素命名,我认为到目前为止我的做法是正确的,使用上面显示的语法创建了一个小的Rule
类。
Now, I have a method within my Parser
class that takes a Rule
parameter:现在,我的Parser
类中有一个采用Rule
参数的方法:
def add(self, dot_rule: Rule):
print(dot_rule.end_pos)
# ...
Unfortunately, following error appears as soon as I try to call an element of dot_rule
like end_pos
:不幸的是,一旦我尝试调用像end_pos
这样的dot_rule
元素,就会出现以下错误:
AttributeError: 'tuple' object has no attribute 'end_pos'
What is it that I misunderstood when using namedtuple
?使用namedtuple
时我误解了什么?
Edit: I call the method add
the following way with lhs
, rhs
, and pos
being some values calculated beforehand:编辑:我调用方法add
以下方式lhs
, rhs
和pos
是一些预先计算的值:
self.add((lhs, rhs, 0, pos, pos))
I thought since namedtuple
is said to be backward-compatible with tuple
this would be the correct syntax.我认为由于据说namedtuple
与tuple
向后兼容,这将是正确的语法。 Apparently, the parameter is now seen as a plain tuple
instead of a Rule
.显然,该参数现在被视为普通tuple
而不是Rule
。 What can I do differently here?我可以在这里做些什么不同的事情?
Edit 2: Traceback message:编辑 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'
You can try this: essentially you were passing it a class tuple instead of the namedtuple called Rule.你可以试试这个:本质上你是在传递一个类元组而不是名为Rule的命名元组。 See:看:
Instead of self.add((lhs, rhs, 0, pos, pos))
而不是self.add((lhs, rhs, 0, pos, pos))
Use self.add(Parser.Rule(lhs, rhs, 0, pos, pos))
使用self.add(Parser.Rule(lhs, rhs, 0, pos, pos))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.