Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Class Variables Question

I have some doubt about python's class variables. As my understanding, if I define a class variable, which is declared outside the __init__() function, this variable will create only once as a static variable in C++.

This seems right for some python types, for instance, dict and list type, but for those base type, e.g. int,float, is not the same.

For example:

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()

The output is:

{1: 2} [1] 1
{1: 2} [1] 3

I understand the results of dict1 and list1, but why does int1 behavior different?

like image 434
YuQing Zhang Avatar asked May 19 '10 12:05

YuQing Zhang


1 Answers

The difference is that you never assign to self.dict1 or self.list1 — you only ever read those fields from the class — whereas you do assign to self.int1, thus creating an instance field that hides the class field.

like image 98
Marcelo Cantos Avatar answered Sep 21 '22 18:09

Marcelo Cantos