Skip to content Skip to sidebar Skip to footer

Two Instances Of Class Share Same Vairable In Python

So this is very wierd. The code below creates 2 instances of MyClass. One would expect that each has its own copy of the private variable __x which is a dictionary. However, my_

Solution 1:

You have to declare __x inside the __init__ function, like this:

classMyClass:def__init__(self, name, init_value):
        self.__x = dict()
        self.__x[name] = init_value

    defget_value(self):
        returnself.__x

Solution 2:

In your case, the way you were defining __x - it was a class variable - i.e. a variable that is shared by all instances of this class.

You can see this if you run a dir on your instances:

dir(my_class1)
['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']

Note the first entry - it is same above and below.

dir(my_class2) 
['_MyClass__x', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value']

Post a Comment for "Two Instances Of Class Share Same Vairable In Python"