Dictionary and array as class and instance variables

This is an easy way to earn points. Please explain the following:

class C:
    a = {}
    b = 0
    c = []

    def __init__(self):
        self.x = {}

    def d(self, k, v):
        self.x[k] = v
        self.a[k] = v;
        self.b = v
        self.c.append(v)

    def out(self, k):
        print(self.x[k], self.a[k], self.b, self.c[0])

c = C()
d = C()
c.d(1, 10)
d.d(1, 20)
c.out(1)  
d.out(1)

Outputs the following:

10 20 10 10
20 20 20 10

Why does the dictionary, list, and "simple" variable behave differently?

Edit: I thought the question was obvious, but let me write it in more detail:

I have a class with three attributes: a, b and c. I create two instances of the class. Then I call a method that modifies these attributes for each instance. When I check the attributes, I find that if the attribute is a dictionary, it is common to all instances, and if it is a "simple" variable, it behaves as you would expect, being different for each instance.

-1
source share
2 answers

, [] , . , .

class Foo(object):
    a = {}
    b = 0
    c = []

- (Foo.a, ), (Foo().a). __dict__. ( , , ), Foo __dict__ , , Foo().a, , Foo.a.

__init__.

class Foo(object):
    # ...

    def __init__(self):
        self.x = {}

'__dict__, , Foo.x, Foo().x. , x - , .

.

class Foo(object):
    # ...

    def mutate(self, key, value):
        self.x[key] = value
        self.a[key] = value
        self.b      = value
        self.c.append(value)

, self.x = {} ? self.b = value - , , (, Python-, , ).

self.a self.c - ( , ) - , ( ). self.x -, , .

self.c - , [10, 20].

+5

a c - b, x - .

Python:

+2

All Articles