Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables without self in a class- Python

Tags:

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?

like image 426
jparikh97 Avatar asked Dec 19 '22 22:12

jparikh97


1 Answers

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
like image 65
mrhn Avatar answered Jan 08 '23 11:01

mrhn