Python类变量或一般类变量 [英] Python class variables or class variables in general

查看:70
本文介绍了Python类变量或一般类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Dive into Python:

From Dive into Python:

通过直接引用 类以及该类的任何实例.

Class attributes are available both through direct reference to the class and through any instance of the class.

类属性可以用作类级常量,但是它们是 不是真正的常数.您也可以更改它们.

Class attributes can be used as class-level constants, but they are not really constants. You can also change them.

所以我将其输入IDLE:

So I type this into IDLE:

IDLE 2.6.5      
>>> class c:
        counter=0


>>> c
<class __main__.c at 0xb64cb1dc>
>>> v=c()
>>> v.__class__
<class __main__.c at 0xb64cb1dc>
>>> v.counter += 1
>>> v.counter
1
>>> c.counter
0
>>> 

那我做错了什么?为什么类变量不能通过直接引用该类以及通过该类的任何实例来保持其值.

So what am I doing wrong? Why is the class variable not maintaining its value both through direct reference to the class and through any instance of the class.

推荐答案

因为int在python中是不可变的

Because ints are immutable in python

v.counter += 1

v.counter重新绑定到新的int对象.重新绑定将创建一个掩盖类属性的实例属性

rebinds v.counter to a new int object. The rebinding creates an instance attribute that masks the class attribute

如果您查看v.counterid()

>>> id(v.counter)
149265780
>>> v.counter+=1
>>> id(v.counter)
149265768

在这里您可以看到v现在在其__dict__

Here you can see that v now has a new attribute in its __dict__

>>> v=c()
>>> v.__dict__
{}
>>> v.counter+=1
>>> v.__dict__
{'counter': 1}

对比counter可变的情况,例如list

Contrast the case where counter is mutable, eg a list

>>> class c:
...  counter=[]
... 
>>> v=c()
>>> v.counter+=[1]
>>> c.counter
[1]
>>> 

这篇关于Python类变量或一般类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆