6

I have a question about why the code below executes what it does.

class Account:
    def __init__(self, id):
        self.id = id
        id = 800
        id = self.id + id

acc = Account(123)
print(acc.id)

Why would this code print 123 instead of 923? Why does the id not work inside of the class?

2
  • 3
    because you are setting id = self.id + id not self.id = self.id + id. id != self.id, they are two completely different variables. acc.id would return the value of self.id Commented Nov 17, 2015 at 22:09
  • Research about the __init__ function Commented Nov 17, 2015 at 22:12

2 Answers 2

11

You declare the variable in the scope to self.id + id, when the init function is finished the scope is gone and therefore id doesn't exist anymore.

Probably, you wanted to do:

self.id += id
Sign up to request clarification or add additional context in comments.

Comments

3

id is local variable inside __init__, you cannot access it outside this method.

When you access to acc.id, you access to the id attribute of the Account class.

Attributes are preceded by self inside the class

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.