我有以下简单的代码
class A:
def __init__(self):
self.value = "789"
def method1(self):
return "valueA"
class B(A):
def __init__(self):
super(B, self).__init__()
def call_parent_method(self):
return super().method1()
def call_parent_value(self):
return super().value
b = B()
print(b.call_parent_method())
print(b.call_parent_value())
b.call_parent_method()
运行良好,而b.call_parent_value()
引发以下异常:
AttributeError: 'super' object has no attribute 'value'
我知道self.value
有效,但我只想知道为什么super().value
无效
因为您继承类属性,但不继承实例属性。它们属于类的特定实例
当您在类
B
中时,value
是B
的实例属性,而不是A
。如果value
是类属性,则可以使用super().value
访问它,例如:Guido van Rossum提供了
super()
中的a pure Python version,这可以清楚地看到super()
是如何工作的(C实现的详细信息在super_getattro()
中的Objects/typeobject.c)看看
__getattr__
的最后一部分,我们会知道super() works for class attribute lookup。上述super().value
相当于super(B, self).__getattr__("value")
相关问题 更多 >
编程相关推荐