在 __init__ 中更改类属性 [英] Changing a class attribute within __init__

查看:48
本文介绍了在 __init__ 中更改类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看堆栈溢出问题计算类的实例?,而且我不确定为什么该解决方案有效,而使用简单加法的解决方案无效.我想这更多是关于如何存储和访问类变量与实例变量的问题.

I was looking at the Stack Overflow question Counting instances of a class?, and I'm not sure why that solution works and one using simple addition doesn't. I guess this is more of a question of how class vs. instance variables are stored and accessed.

这是我认为应该工作的代码,但是为每个 id 生成 4 :

Here's the code I think should work, but instead produces 4 for every id:

class foo():
      num = 3    # trying 3 instead of 0 or 1 to make sure the add is working

      def __init__(self):
        self.num += 1
        self.id = self.num

f = foo()
g = foo()

print f.id    # 4
print g.id    # 4

self.num +=1 语句有点工作(添加发生,但不是赋值).

The self.num +=1 statement is somewhat working (the addition is happening, but not the assignment).

到底发生了什么导致此分配在这里失败,而 itertools.count 分配在另一个问题的解决方案中成功?

What is happening under the hood that's making this assignment fail here, while the itertools.count assignment succeeds in the other question's solution?

推荐答案

self.num += 1 的意思是,基本上,'取self.num的值,增加它,并分配给 self.num.

self.num += 1 means, basically, 'take the value of self.num, increment it, and assign to self.num.

self上查找一个属性,如果没有对应的实例变量,就会找到类变量.但是,赋值将始终写入实例变量.因此,这会尝试查找实例 var,失败,返回到类 var,获取值,递增它,然后将分配给实例 var.

Looking up an attribute on self will find the class variable if there is no corresponding instance variable. However, assigning will always write to an instance variable. So, this tries to find an instance var, fails, falls back to a class var, gets the value, increments it, then assigns to an instance var.

链接问题的答案有效的原因是因为没有进行分配;它们直接在类变量上调用 next(),它的值发生了变化,但名称没有重新分配.

The reason the answer to the linked question works is because there is no assigning going on; they call next() directly on the class variable, its value is mutated but the name is not reassigned.

这篇关于在 __init__ 中更改类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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