Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: can't set attribute in python

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].v value to node.v as I want, and am getting the error

"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+=1 is also showing same error. I'm new to Python, so please suggest a way to make the above change possible.

like image 413
Pratyush Dhanuka Avatar asked Mar 21 '14 15:03

Pratyush Dhanuka


People also ask

How do I fix AttributeError in Python?

Solution for AttributeError Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised.

How do you set attributes in Python?

Use the setattr() Function to Set Attributes of a Class in Python. Python's setattr() function is used to set values for the attributes of a class. In programming, where the variable name is not static, the setattr() method comes in very handy as it provides ease of use.

Why am I getting AttributeError object has no attribute?

It's simply because there is no attribute with the name you called, for that Object. This means that you got the error when the "module" does not contain the method you are calling.


2 Answers

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

like image 195
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 14:09

Ignacio Vazquez-Abrams


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.

like image 23
jonrsharpe Avatar answered Sep 17 '22 14:09

jonrsharpe