class variables is shared across all instances in python? [duplicate] class variables is shared across all instances in python? [duplicate] python python

class variables is shared across all instances in python? [duplicate]


var should definitely not be shared as long as you access it by instance.var or self.var. With the list however, what your statement does is when the class gets evaluated, one list instance is created and bound to the class dict, hence all instances will have the same list. Whenever you set instance.list = somethingelse resp. self.list = somethingelse, it should get an instance level value.

Example time:

>>> class A():...     var = 0...     list = []...>>> a = A()>>> b = A()>>> a.var0>>> a.list[]>>> b.var0>>> b.list[]>>> a.var = 1>>> b.var0>>> a.list.append('hello')>>> b.list['hello']>>> b.list = ['newlist']>>> a.list['hello']>>> b.list['newlist']


These are basically like static variables in Java:

// Example equivalent Javaclass A {    static int var = 0;    static String[] list;}

This is the intended behavior: Class variables are for the class.

For normal instance variables, declare them in the constructor:

class A:    def __init__(self):        self.var = 0        self.list = []

You may want to look at Static class variables in Python.


The reason is that in Python class is an executable statement that is executed like any other. The body of the class definition is executed once, when the class is defined. If you have a line line var = [] in there, then it is only executed once, so only one list can ever be created as a result of that line.