复合赋值给Python类和实例变量 [英] Compound assignment to Python class and instance variables

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

问题描述

我一直在试图理解Python对类和实例变量的处理。特别是,我发现这个答案非常有帮助。基本上,它说如果你声明一个类变量,然后你做一个赋值 [instance] .property ,你将被分配到一个不同的变量 -



所以我考虑 - 如果我想让我的类的每个实例都有一个默认值(如零)的成员,我应该这样做:

  class Foo:
num = 0



还是这样?

  class Foo :
def __init __(self):
self.num = 0

在我之前读到的,我认为第二个例子将初始化正确变量(实例而不是类变量)。但是,我发现第一种方法也很好地工作:

  class Foo:
num = 0

bar = Foo()
bar.num + = 1#好,没有错误,意味着bar有一个属性'num'
bar.num
> ;> 1
Foo.num
>>>> 0#但类变量没有修改!所以我刚才补充的是什么?

那么,为什么这么做?我没有得到什么? FWIW,我之前对OOP的理解来自于C ++,所以通过类比来解释(或指向它的分解)可能是有用的。

解决方案

就我个人而言,我发现Shalabh Chaturvedi的这些文件非常实用



bar.num + = 1 bar.num = bar.num + 1 。这是在右侧拾取类变量 Foo.num ,并将其赋给一个实例变量 bar.num


I've been trying to understand Python's handling of class and instance variables. In particular, I found this answer quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to [instance].property, you will be assigning to a different variable altogether -- one in a different namespace from the class variable.

So then I considered -- if I want every instance of my class to have a member with some default value (say zero), should I do it like this:

class Foo:
    num = 0

or like this?

class Foo:
    def __init__(self):
        self.num = 0

Based on what I'd read earlier, I'd think that the second example would be initializing the 'right' variable (the instance instead of the class variable). However, I find that the first method works perfectly well too:

class Foo:
    num = 0

bar = Foo()
bar.num += 1 # good, no error here, meaning that bar has an attribute 'num'
bar.num
>>> 1
Foo.num
>>> 0 # yet the class variable is not modified! so what 'num' did I add to just now?

So.. why does this work? What am I not getting? FWIW, my prior understanding of OOP has come from C++, so explanation by analogy (or pointing where it breaks down) might be useful.

解决方案

Personally, I've found these documents by Shalabh Chaturvedi extremely useful and informative regarding this subject matter.

bar.num += 1 is a shorthand for bar.num = bar.num + 1. This is picking up the class variable Foo.num on the righthand side and assigning it to an instance variable bar.num.

这篇关于复合赋值给Python类和实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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