Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: differences between init method and in-class declare?

Tags:

python

is there any difference between these two method? option1 :

class a(object):
    def __init__(self):
        self.x = 123
        self.y = 345

option2 :

class a(object):
        x = 123
        y = 345

is there any difference between these two options? Thanks in advance.

like image 254
dzhwinter Avatar asked Nov 22 '25 11:11

dzhwinter


1 Answers

An example of the first method (instance level variables):

instance0 = a()
instance1 = b()

instance0.x = 5
print instance1.x # prints 123

print a.x  # undefined variable - x is not defined

An example of the second method (class level variables):

instance0 = a()
instance1 = b()

instance0.x = 5
print instance1.x # prints 5

print a.x  # prints 5

The second method, the variables are assigned at the class level meaning changing this value propagates to all instances of that class. You can also access the variables without an instance of the class.

like image 145
14 revs, 12 users 16% Avatar answered Nov 25 '25 01:11

14 revs, 12 users 16%