A
A
Alexey2014-12-09 18:26:28
Python
Alexey, 2014-12-09 18:26:28

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

This code outputs
{'a': 3, 'b': 4}
{'a': 3, 'b': 4}

How to make the dictionary unique, poke into the documentation.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey K, 2014-12-09
@rdifb0

class SomeClass:
    def __init__(self):
        self.attr_dic = {'a': 1, 'b': 2}

L
lPolar, 2014-12-10
@lPolar

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

B
bromzh, 2014-12-10
@bromzh

Because you need to read literature. You declare a class variable. It will be common to all instances of your class. And they are used, for example, to store information needed by all instances.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question