Answer the question
In order to leave comments, you need to log in
Why is a dictionary as an attribute not unique?
class SomeClass:
attr_dic = {'a': 1, 'b': 2}
some_a = SomeClass()
some_b = SomeClass()
some_a.attr_dic['a'] = 3
some_b.attr_dic['b'] = 4
print some_a.attr_dic
print some_b.attr_dic
{'a': 3, 'b': 4}
{'a': 3, 'b': 4}
Answer the question
In order to leave comments, you need to log in
It seems to me that in this case, the attr_dic variable defined in the SomeClass class, when using this class, remains common for all objects of this class (clumsily written, but illustrative example in python 3):
class SomeClass:
attr_dic = {'a': 1, 'b': 2}
class OtherClass:
def __init__(self):
self.attr_dic={'a':1,'b':2}
some_a = SomeClass()
some_b = SomeClass()
print('some_a adress %i'%id(some_a)) #выведет 204146672
print('some_b adress %i'%id(some_b)) # выведет 204148720
print('some_a dict adress %i'%id(some_a.attr_dic)) # 204166128
print('some_b dict adress %i'%id(some_b.attr_dic)) # 204166128
other_a = OtherClass()
other_b = OtherClass()
print('other_a adress %i'%id(other_a)) #204145392
print('other_b adress %i'%id(other_b)) #204148592
print('other_a dict adress %i'%id(other_a.attr_dic)) #204165448
print('other_b dict adress %i'%id(other_b.attr_dic)) #204115000
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question