类变量的行为类似于实例变量(Python 3.4) [英] Class Variable behaving like Instance Variable (Python 3.4)

查看:118
本文介绍了类变量的行为类似于实例变量(Python 3.4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.4.0a1
Windows 8.1

Python 3.4.0a1
Windows 8.1

创建的类:

class Bank(object):  
    bankrupt = False  

在IDLE __main__中输入的命令具有以下结果:

Command entered in IDLE __main__ with the following results:

>>> a = Bank()
>>> b = Bank()
>>> a.bankrupt
False
>>> b.bankrupt
False
>>> b.bankrupt = True
>>> b.bankrupt
True
>>> a.bankrupt
False

预期输出:

我希望当我更改b.bankrupt时,a.bankrupt会更改为True,因为为整个类而不是单个实例(使用self.bankrupt)定义了变量bankrupt,为什么没有发生这种情况?

Expected output:

I expected a.bankrupt to change to True when I changed b.bankrupt since the variable bankrupt is defined for the entire class and not for a single instance (with self.bankrupt) Why is this not happening?

推荐答案

您已为实例分配了新属性.要更改类属性,请直接分配给该类.

You assigned to a new attribute to the instance instead. To change a class attribute, assign directly to the class.

在实例上查找属性时,查找进入"类,然后进入基类.这就是找到所有类属性(包括方法)的方式.

When looking up an attribute on an instance, look-up 'falls through' to the class, then to the base classes. This is how all class attributes, including methods, are found.

但是分配时,这直接发生在实例上.否则,您将永远无法分配每个实例的值,只能分配回该类.分配给a.bankruptb.bankrupt会为实例添加一个属性,如果该属性尚未开始的话.对于Python,在方法中使用self.bankrupt = True或从外部"使用a.bankrupt = True分配给属性没有区别.

But when assigning, this happens directly on the instance. Otherwise you could never assign per-instance values, you'd only ever assign back to the class. Assigning to a.bankrupt or b.bankrupt will add an attribute to the instance, if it wasn't already there to begin with. To Python, there is no difference between using self.bankrupt = True in a method, or to using a.bankrupt = True from the 'outside' to assign to an attribute.

只需直接(从方法或外部")分配给class属性:

Just assign to the class attribute directly (from a method or from 'outside'):

Bank.bankrupt = True

请注意,相同的读取失败,写入规则分配也适用于基类.如果没有直接在类上找到属性,则在类上查找属性将查找基类,但是直接在类上设置属性则不会影响基类上的属性.

Note that the same fall-through on read, assignment on write rules apply to base classes; looking up an attribute on a class looks to the base classes if the attribute is not found on the class directly, but setting an attribute on a class do so directly, and not affect attributes on the bases.

有关具体细节,请参见

For the nitty gritty details, see the Custom classes and Class instances sections of the Python datamodel.

这篇关于类变量的行为类似于实例变量(Python 3.4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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