开发者

Python Class Variables Question

开发者 https://www.devze.com 2022-12-30 16:31 出处:网络
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

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 in开发者_运维问答t1 behavior different?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消