Robert3452
Robert3452

Reputation: 1496

Python dictionary types as instance variables

I think I am going mad. I did the following in the repel (python3):

class aClass():
  da = {}

>>> a = aClass()
>>> b = aClass()
>>> a.da['T'] = 'Hello'
>>> print(a.da)
{'T': 'Hello'}
>>> print(b.da)
{'T': 'Hello'}
>>>

a and b are two different instances of the same class. I assigned something to a, why is it appearing in b?

I did the same but with a string type, no problem at all.

The following works:

>>> a={}
>>> b={}
>>> print(a)
{}
>>> print(b)
{}
>>> a['x']='x'
>>> print(a)
{'x': 'x'}
>>> print(b)
{}

but, that's exactly the same thing isn't it?

Upvotes: 0

Views: 51

Answers (1)

khelwood
khelwood

Reputation: 59185

aClass.da is a class attribute, not an instance attribute. a.da and b.da are the same dictionary.

Create the dictionary in an __init__ method instead.

class aClass:
    def __init__(self):
        self.da = {}

(In Python 2, that should be class aClass(object): instead.)

Result:

>>> a = aClass()
>>> b = aClass()
>>> a.da['T'] = 'Hello'
>>> print(a.da)
{'T': 'Hello'}
>>> print(b.da)
{}

Upvotes: 8

Related Questions