问题描述
这里有一个关于实例变量的新手Python问题。
Here's a bit of a newbie Python question about instance variables.
请考虑以下Python 2.7类定义:
Consider the following Python 2.7 class definition:
class Foo(object):
a = 1
def __init__(self):
self.b = 2
def __repr__(self):
return "%s" % self.__dict__
现在,当我创建 Foo
的实例时, Foo .__ dict __
包含 b
,但不是 a
。
Now, when I create an instance of Foo
, Foo.__dict__
contains b
, but not a
.
>>> x=Foo()
>>> x
{'b': 2}
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', 'a', 'b']
>>> x.__dict__
{'b': 2}
在这里,我以为我有一个相当了解Python的方式。
And here I thought I had a pretty good grasp on the Way of the Python.
x.a
和 x.b
有什么区别?据我所知,它们都是实例变量。
What's the difference between x.a
and x.b
? As far as I can tell they're both instance variables.
编辑:好的,重新读取我看到 Foo.a
是 class属性,而不是实例变量。嗯...我猜是因为我可以为 xa
分配一个新值,而新值只会影响 x
实例-我想我现在在 Foo.a
属性顶部的成员变量中使用别名:
Edit: OK, re-reading the Python docs I see that Foo.a
is a class attribute rather than an instance variable. Hm... I guess the confusion comes from the fact that I can assign a new value to x.a
and the new value only affects the x
instance -- I suppose I'm now aliasing a member variable over the top of the Foo.a
attribute:
>>> y=Foo()
>>> y.a = 2
>>> y
{'a': 2, 'b': 2}
>>> x
{'b': 2}
>>> x.a
1
>>> z=Foo()
>>> z
{'b': 2}
>>> z.a
1
>>> Foo.a
1
>>> x.a
1
>>> y.a
2
所以,现在我覆盖了以前的 Foo.a
,它会影响所有 Foo
没有别名为 Foo.a $ c $的实例c>:
So, now I overwrite the previous value of Foo.a
, and it affects all instances of Foo
that haven't aliased Foo.a
:
>>> Foo.a=999
>>> x.a
999
>>> y.a
2
推荐答案
您的 a
不是实例变量。您将其定义为类的一部分。
Your a
isn't an instance variable. You defined it as part of the class.
>>> class Foo(object):
... a = 1
...
>>> Foo.a
1
如果要使用实例变量,应将其放在 __ init __
方法,因为在创建对象时会调用此方法。
If you want an instance variable you should put it inside the __init__
method, because this method is called when your object is created.
这篇关于Python类实例__dict__并不包含所有实例变量。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!