Search code examples
python-3.xlistpython-3.8instance-variablesclass-variables

Problem encountered while using list as a class variable in python3.8


I am trying to learn the python class variable concepts, while doing so I have encountered below issue. I would appreciate if anyone can help me in understanding why this below mentioned behavior

Python Version 3.8

class a:
    A = 6
    list_a = []
    def __init__(self, b , c):
        self.b = b
        self.c =c
    def print_all(self):
        print(self.b)
        print(self.c)
        self.list_a.append(5)

This class has b & c as instance variables, and A as class variable also list_a list as class variable

without any object instance

>>> a.A
6
>>> a.list_a
[]

with object-1

>>> ABC = a(4,3)
>>> ABC.A
6
>>> ABC.list_a
[]
>>> ABC.A = 10
>>> ABC.A
10
>>> a.A
6
>>> a.A = 20
>>> a.A 
20
>>> ABC.A
10
>>> ABC.print_all()
4
3
>>> ABC.list_a
[5]
>>> a.list_a
[5]

if you observe the above code, updating A variable through ABC object is not reflecting in a.A, also applicable vice versa but Updating List **list_a ** either through object ABC or class variable a.list_a is reflecting both in object instance and Globally

similarly with Object-2

>>> BBB = a(6,9)
>>> BBB.list_a
[5]
>>> BBB.A
6
>>> ABC.print_all()
4
3
>>> BBB.list_a
[5, 5]
>>> a.list_a
[5, 5]
>>> BBB.A = 17
>>> BBB.A
17
>>> ABC.A
10
>>> a.A
20
>>> BBB.print_all()
6
9
>>> a.list_a
[5, 5, 5]
>>> ABC.list_a
[5, 5, 5]
>>> BBB.list_a
[5, 5, 5]

Here also any changes to the list_a from any object of the class is reflecting across all the instances of class, while variable A is not

Why updating the class variable A from instances of class is not reflecting across the all other instances while update to List is flowing across other instances of class


Solution

  • This is probably the same issue as a list as default argument of a function: https://web.archive.org/web/20200221224620id_/http://effbot.org/zone/default-values.htm