2

I have a class Player, and i am trying to edit one of its attributes. However, I keep on coming up with an error in a for loop within my method:

class Player:
     #bunch of attributes
     X = 1
     Y = 1
def foo(self, bar):
    for i in [X,Y]:
        self.i += bar.i

However, this error shows up:

AttributeError: Player instance has no attribute 'i'

What is causing this error?

3
  • Looks like you're looking for getattr. Also, your code will actually raise NameError since there's no variable called item. Commented Jan 7, 2016 at 19:29
  • self.i has not been declared anywhere in the program (doesn't exist as the error message says). Note that "item" does not exist either in the code you posted, and foo() does not know what "X" and "Y" are, and the function is never called. One tutorial explaining scope en.wikibooks.org/wiki/Python_Programming/Classes Commented Jan 7, 2016 at 19:29
  • I meant to switch item with bar, my bad Commented Jan 7, 2016 at 21:00

2 Answers 2

2

self.i try to access the attribute i of your class regardless of the value that i contain, and as your class don't have such attribute you get a error, if you want to access the attribute by the value of some variable you need to use getattr, and do something like this

>>> class Player:
    X=23
    Y=32
    def foo(self):
        for i in ["X","Y"]:
            print i
            print getattr(self,i)


>>> a=Player()
>>> a.foo()
X
23
Y
32
>>> 
Sign up to request clarification or add additional context in comments.

Comments

1

Variable i is a throwaway variable which exist in local scope of your function and reassigned in each iteration. If you want to change multiple variable like this in your class scope, you better to use a list and change the list items within your function:

>>> class Player:
...    def __init__(self):
...        self.Lst = [1,1]
...    def foo(self, bar):
...        self.Lst = [i+bar for i in self.Lst]
... 
>>> 
>>> P = Player()
>>> P.Lst
[1, 1]
>>> P.foo(2)
>>> P.Lst
[3, 3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.