[英]AttributeError: can't set attribute - Python instance attribute assignment
[英]AttributeError: can't set attribute in python
這是我的代碼
N = namedtuple("N", ['ind', 'set', 'v'])
def solve():
items=[]
stack=[]
R = set(range(0,8))
for i in range(0,8):
items.append(N(i,R,8))
stack.append(N(0,R-set(range(0,1)),i))
while(len(stack)>0):
node = stack.pop()
print node
print items[node.ind]
items[node.ind].v = node.v
在最后一行中,我無法根據需要將items[node.ind].v
值設置為node.v
,並且出現錯誤
"AttributeError: can't set attribute"
我不知道出了什么問題,但它必須是基於語法的東西,因為使用像node.v+=1
這樣的語句也顯示相同的錯誤。 我是 Python 新手,所以請提出一種使上述更改成為可能的方法。
items[node.ind] = items[node.ind]._replace(v=node.v)
(注意:不要因為函數 _replace 中的前導下划線而氣餒使用此解決方案。特別是對於 namedtuple,某些函數具有前導下划線,這並不是為了表明它們是“私有的”)
namedtuple
是不可變的,就像標准元組一樣。 你有兩個選擇:
前者看起來像:
class N(object):
def __init__(self, ind, set, v):
self.ind = ind
self.set = set
self.v = v
而后者:
item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)
編輯:如果你想要后者,伊格納西奧的回答使用內置功能更巧妙地做同樣的事情。
對於那些搜索此錯誤的人,可能觸發AtributeError: can't set attribute
的另一件事是,如果您嘗試設置沒有 setter 方法的修飾@property
。 不是 OP 問題中的問題,但我把它放在這里是為了幫助任何直接搜索錯誤消息。 (如果你不喜歡它,去編輯問題的標題:)
class Test:
def __init__(self):
self._attr = "original value"
# This will trigger an error...
self.attr = "new value"
@property
def attr(self):
return self._attr
Test()
如果您嘗試重新定義已在您繼承的類中定義的成員變量,則可能會觸發此錯誤。
from pytorch_lightning import LightningModule
class Seq2SeqModel(LightningModule):
def __init__(self, tokenizer, bart, hparams):
super().__init__()
self.tokenizer = tokenizer
self.bart: BartForConditionalGeneration = bart
self.hparams = hparams # This triggers the error
# Changing above line to below removes the error
# self.hp = hparams
由於我是PyTorch
和PyTorch Lightning
的新手,我不知道LightningModule
已經有一個名為self.hparams
的成員變量。 當我試圖在我的代碼中覆蓋它時,它導致了AttributeError: can't set attribute
。
只需簡單地將我的變量從self.hparams
重命名為其他內容即可消除錯誤。
不是OP問題中的問題,但我把它放在這里是為了幫助任何直接搜索錯誤消息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.