[英]Object vs. class variable
这是一个完全理论化的问题。 假设以下代码:
>>> 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
访问吗?
是的,虽然c.__class__.a
或type(c).a
。 两者的区别在于旧式的类(希望,那些现在都已经死了 - 但你永远不知道......)有一个<type 'instance'>
__class__
<type 'instance'>
的type()
(和__class__
按预期工作)而对于new样式类, type()
与__class__
相同,除非对象覆盖属性访问。
所有类变量都可以通过从该类实例化的对象访问。
>>> class C:
... a = 10
... def f(self): self.a = 999
...
>>> C.a
10
>>> c = C()
>>> c.a
10
>>> c.f()
>>> c.a
999
>>> c.__class__.a
10
>>> c.a
999
>>> del(c.a)
>>> c.a
10
首先在对象命名空间中搜索属性,然后在类中搜索。
是的,你可以访问a
从对象c
,点菜ca
。 该值最初为10。
但是,如果你调用cf()
, ca
的值现在将是999, 但是 Ca
仍然是10.同样,如果你现在将Ca
改为1000,那么ca
仍然是999。
基本上,当您实例化C
的实例时,它将使用类变量作为其自己a
值, 直到您更改该实例的值a
,在这种情况下,它将不再与该类“共享” a
。
后分配给它的类的实例,有两个命名类属性a
和命名实例属性a
。 我举例说明:
>>> class Foo(object):
... a = 10
...
>>> c = Foo()
>>> c.a
10
>>> c.a = 100 # this doesn't have to be done in a method
>>> c.a # a is now an instance attribute
100
>>> Foo.a # that is shadowing the class attribute
10
>>> del c.a # get rid of the instance attribute
>>> c.a # and you can see the class attribute again
10
>>>
不同之处在于,一个作为Foo.__dict__
中的条目存在,另一个作为c.__dict__
的条目存在。 当你访问instance.attribute
,如果它存在,则返回instance.__dict__['attribute']
,如果不存在,则返回type(instance).__dict__['attribute']
。 然后检查类的超类,但稍微复杂一点。
但无论如何,重点是它不必是一个或另一个。 类和实例都可以具有相同名称的不同属性,因为它们存储在两个单独的dicts中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.