Mahardhika Praja
Mahardhika Praja

Reputation: 23

Global variable in class shared to other instance

I need explanation about code below

class Test():
    a_variable = []

    def add(self, value):
        self.a_variable.append(value)

    def print(self):
        print(self.a_variable)

a = Test()
b = Test()

a.add(1)
b.print()

Output

[1]

Questions:

  1. Is it normal?
  2. Why a_variable shared to other instance?
  3. Is there any documentation about this?

Note: I'm using python 3.7.4 in my environment and running on Windows 10

Upvotes: 2

Views: 63

Answers (1)

Selcuk
Selcuk

Reputation: 59164

Normally when you try to set a class attribute using an instance, you create an object attribute that shadows the class attribute. For example, if you do the following:

def add(self, value):
    self.a_variable = value

You will end up with:

a.print() will print 1

b.print() will print []

By using .append(), you fetch a reference to the class attribute (i.e. Test.a_variable) and mutate it. That's why it is reflected to all instances of the class.

Upvotes: 4

Related Questions