AttributeError:无法在python中设置属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22562425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:10:34  来源:igfitidea点击:

AttributeError: can't set attribute in python

pythonattributes

提问by Pratyush Dhanuka

Here is my code

这是我的代码

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

In the last line I cant set the items[node.ind].vvalue to node.vas I want, and am getting the error

在最后一行中,我无法将items[node.ind].v值设置node.v为我想要的,并且出现错误

"AttributeError: can't set attribute"

I don't know what's wrong but it must be something based on syntax as using statements like node.v+=1is also showing same error. I'm new to Python, so please suggest a way to make the above change possible.

我不知道出了什么问题,但它必须基于语法,因为 using 语句node.v+=1也显示相同的错误。我是 Python 新手,所以请提出一种方法来使上述更改成为可能。

采纳答案by Ignacio Vazquez-Abrams

items[node.ind] = items[node.ind]._replace(v=node.v)

(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")

(注意:不要因为函数 _replace 中的前导下划线而气馁使用此解决方案。特别是对于namedtuple,一些函数有前导下划线,这并不是为了表明它们是“私有的”)

回答by jonrsharpe

namedtuples are immutable, just like standard tuples. You have two choices:

namedtuples 是不可变的,就像标准元组一样。你有两个选择:

  1. Use a different data structure, e.g. a class (or just a dictionary); or
  2. Instead of updating the structure, replace it.
  1. 使用不同的数据结构,例如一个类(或只是一个字典);或者
  2. 与其更新结构,不如替换它。

The former would look like:

前者看起来像:

class N(object):

    def __init__(self, ind, set, v):
        self.ind = ind
        self.set = set
        self.v = v

And the latter:

而后者:

item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)

Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.

编辑:如果你想要后者,伊格纳西奥的回答使用内置功能更巧妙地做同样的事情。