对象与类变量
这是一个完全理论上的问题。假设有以下代码:
>>> class C:
... a = 10
... def f(self): self.a = 999
...
>>>
>>> C.a
10
>>> c = C()
>>> c.a
10
>>> c.f()
>>> c.a
999
此时,类变量Ca 是否仍然可以通过对象c 访问?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,尽管
c.__class__.a
或type(c).a
。两者略有不同,旧式类(希望这些现在都已经死了 - 但你永远不知道......)的type()
为
(并且__class__
按预期工作),而对于新式类,type()
与__class__
相同,除非对象覆盖属性访问。Yes, though
c.__class__.a
ortype(c).a
. The two differ slightly in that old-style classes (hopefully, those are all dead by now - but you never know...) have atype()
of<type 'instance'>
(and__class__
works as expected) while for new-style classes,type()
is identical to__class__
except when the object overrides attribute access.在类实例上分配给它后,就会有一个名为
a
的类属性和一个名为a
的实例属性。我举例说明:区别在于,一个作为
Foo.__dict__
中的条目存在,另一个作为c.__dict__
中的条目存在。当您访问instance.attribute
时,如果存在,则返回instance.__dict__['attribute']
,如果不存在,则返回type(instance).__dict__['attribute ']
已检查。然后检查该类的超类,但这会变得稍微复杂一些。但无论如何,要点是不一定非得是其中之一。类和实例都可以具有具有相同名称的不同属性,因为它们存储在两个单独的字典中。
After you assign to it on the class instance, there is both a class attribute named
a
and an instance attribute nameda
. I illustrate:The difference is that one exists as an entry in
Foo.__dict__
and the other exists as an entry inc.__dict__
. When you accessinstance.attribute
,instance.__dict__['attribute']
is returned if it exists and if not thentype(instance).__dict__['attribute']
is checked. Then the superclasses of the class are checked but that gets slightly more complicated.But at any rate, the main point is that it doesn't have to be one or the other. A class and an instance can both have distinct attributes with identical names because they are stored in two separate dicts.
所有类变量都可以通过从该类实例化的对象来访问。
首先在对象命名空间中搜索属性,然后在类中搜索。
All class variables are accessible through objects instantiated from that class.
Attributes are first searched within the object namespace and then class.
是的,您可以从对象
c
访问a
,就像ca
一样。该值最初为 10。但是,如果您调用
cf()
,ca
的值现在将为 999,但是Ca
仍将是 10。同样,如果您现在将Ca
更改为 1000,ca
仍将是 999。基本上,当您实例化一个实例时对于
C
,它将使用类变量作为自己的a
值,直到您更改该实例的a
值code>,在这种情况下,它将不再与类“共享”a
。Yes, you can access
a
from an objectc
, à lac.a
. The value would initially be 10.However, if you call
c.f()
, the value ofc.a
will now be 999, butC.a
will still be 10. Likewise, if you now changeC.a
to, say, 1000,c.a
will still be 999.Basically, when you instantiate an instance of
C
, it will use the class variable as its owna
value, until you change the value of that instance'sa
, in which case it will no longer "share"a
with the class.