Reputation: 729
Suppose I have a class, call it class1,
with 3 class variables var1,var2,var3,
and __init__
method, which assigns passed arguments to the class variables:
class class1(object):
var1 = 0
var2 = 0
var3 = 0
def __init__(self,a,b,c):
class1.var1 = a
class1.var2 = b
class1.var3 = c
Now I'm going to make two instances of the same class:
obj1 = class1(1,2,3)
obj2 = class1(4,5,6)
And now, let's take a look at variables values:
print (obj1.var1, obj1.var2,obj1.var3)
4 5 6
print (obj2.var1, obj2.var2,obj2.var3)
4 5 6
Shouldn't obj1
have values 1,2,3 ? Why __init__
method of the second instance changes vaues in the first instance(obj1
)? And how to make two independent separate instances of a class?
Upvotes: 1
Views: 115
Reputation: 34146
Variables declared in the class definition, but not inside a method, will be class variables. In other words, they will be the same for the whole class.
To solve this you could declare them in the __init__
method, so they become instance variables:
class class1():
def __init__(self,a,b,c):
self.var1 = a
self.var2 = b
self.var3 = c
Upvotes: 4
Reputation: 368904
Class variables are shared by all instances of the class (and the class itself). You need to use instance variables instead.
>>> class class1(object):
... def __init__(self,a,b,c):
... self.var1 = a
... self.var2 = b
... self.var3 = c
...
>>> obj1 = class1(1,2,3)
>>> obj2 = class1(4,5,6)
>>> print (obj1.var1, obj1.var2,obj1.var3)
(1, 2, 3)
>>> print (obj2.var1, obj2.var2,obj2.var3)
(4, 5, 6)
Upvotes: 2