1

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?

2
  • You have specifically made these class, not instance, attributes. If you want instance attributes, use e.g. self.var1 = a, and remove the assignments outside __init__. Commented Mar 19, 2014 at 15:47
  • see here stackoverflow.com/questions/68645/… Commented Mar 19, 2014 at 15:50

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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)

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.