jparikh97
jparikh97

Reputation: 105

Using variables without self in a class- Python

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?

Upvotes: 6

Views: 10864

Answers (2)

mrhn
mrhn

Reputation: 18916

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

Upvotes: 10

Loïc G.
Loïc G.

Reputation: 3157

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

Upvotes: 3

Related Questions