I have some doubts about python class variables. As I understand it, if I define a class variable declared outside the __init__() function, this variable will be created only once as a static variable in C ++.
This seems correct for some python types, for example for the dict and list types, but for the base type, for example. int, float, not the same.
For instance:
class A: dict1={} list1=list() int1=3 def add_stuff(self, k, v): self.dict1[k]=v self.list1.append(k) self.int1=k def print_stuff(self): print self.dict1,self.list1,self.int1 a1 = A() a1.add_stuff(1, 2) a1.print_stuff() a2=A() a2.print_stuff()
Conclusion:
{1: 2} [1] 1 {1: 2} [1] 3
I understand the results of dict1 and list1, but why is the behavior of int1 different?
source share