1 year ago
#258942
saint_sharan
Python: anomaly in value of class-variables of different type after changing its value
I was trying to understand the scope of class variables. Value of class variables (string and list type) of parent class, after changing its value using the instance object of its derived class, showed different behavior. When I changed the class variable value of string type from subclass object, it was changed for that subclass instance only. On the other hand, when I changed the value of the class variable of LIST type from the instance of the subclass, the change was reflected everywhere (instance of parent class, parent class variable, instance of subclass, and subclass class variable from parent class). Below I have emulated the problem in the concise manner. This is just for reference, not the actual code from the codebase.
class A:
list_var = [1]
str_var = 'a'
class B(A):
pass
print(A.list_var, A.str_var, B.list_var, B.str_var, "\n")
a_obj = A()
b_obj = B()
print(a_obj.list_var, a_obj.str_var, b_obj.list_var, b_obj.str_var) # similar values observerd when accessed using A.list_var, etc.
b_obj.list_var.append(2) # this change can be seen everywhere
b_obj.str_var = b_obj.str_var + 'b' # this change can only be seen with this instance, NOT at anywhere else.
# proof
print("\n", A.list_var, A.str_var, B.list_var, B.str_var)
print(a_obj.list_var, a_obj.str_var, b_obj.list_var, b_obj.str_var)
python
python-3.x
inheritance
class-variables
shallow-copy
0 Answers
Your Answer