AttributeError: can't set attribute in python

前端 未结 3 1254
旧时难觅i
旧时难觅i 2020-12-15 02:35

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):
              


        
相关标签:
3条回答
  • 2020-12-15 02:43

    For those searching this error, another thing that can trigger AtributeError: can't set attribute is if you try to set a decorated @property that has no setter method. Not the problem in the OP's question, but I'm putting it here to help any searching for the error message directly. (if you don't like it, go edit the question's title :)

    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()
    
    0 讨论(0)
  • 2020-12-15 02:47

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

    1. Use a different data structure, e.g. a class (or just a dictionary); or
    2. Instead of updating the structure, replace it.

    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.

    0 讨论(0)
  • 2020-12-15 03:01
    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")

    0 讨论(0)
提交回复
热议问题