在类定义期间,没有任何继承的属性可用:
>>> class Super(object):
class_attribute = None
def instance_method(self):
pass
>>> class Sub(Super):
foo = class_attribute
Traceback (most recent call last):
File "", line 1, in
class Sub(Super):
File "", line 2, in Sub
foo = class_attribute
NameError: name 'class_attribute' is not defined
>>> class Sub(Super):
foo = instance_method
Traceback (most recent call last):
File "", line 1, in
class Sub(Super):
File "", line 2, in Sub
foo = instance_method
NameError: name 'instance_method' is not defined
您甚至无法使用super访问它们,因为子类的名称未在定义块*中定义:
>>> class Sub(Super):
foo = super(Sub).instance_method
Traceback (most recent call last):
File "", line 1, in
class Sub(Super):
File "", line 2, in Sub
foo = super(Sub).instance_method
NameError: name 'Sub' is not defined
在定义时访问继承属性的唯一方法是使用超类的名称显式地这样做:
>>> class Sub(Super):
foo = Super.class_attribute
>>> Sub.foo is Super.class_attribute
True
或者,您可以在类或实例方法中访问它们,但是您需要使用类的适当前缀(常规cls)或实例(常规自身)参数.
*对于任何想“啊,但在3.x你不需要超级论证”的人:
>>> class Sub(Super):
foo = super().instance_method
Traceback (most recent call last):
File "", line 1, in
class Sub(Super):
File "", line 2, in Sub
foo = super().instance_method
RuntimeError: super(): no arguments
这在实例/类方法中是唯一的!