超类有实例属性
b
,我尝试使用super()
方法访问它,那么为什么我得到Attribute Error
?它应该访问超类的实例变量,但它给出了属性错误,任何人请告诉我哪里错了。
这里定义了超类
P
子类
C
继承类P
class P:
a = 10
def __init__(self):
self.b = 20
def m1(self):
print("Parent instance method")
@classmethod
def m2(cls):
print("Parent class method")
@staticmethod
def m3():
print("Parent static method")
class C(P):
a = 888
def __init__(self):
self.b = 999
super().__init__()
print(super().a)
print(super().b)
c = C()
输出
PS D:\python_practice> python .\test.py
10
Traceback (most recent call last):
File ".\test.py", line 21, in <module>
c = C()
File ".\test.py", line 19, in __init__
print(super().b)
AttributeError: 'super' object has no attribute 'b'
super()
用于在类方法解析顺序 (MRO) 中的后续 class 上查找属性(通常是方法,但如您所见,它也适用于类属性)。实例属性并不与层次结构中的特定类绑定(它们都存储在实例本身上,通常在底层的单个 dict
中),您只需直接在 self
上查找它们即可。
super()
对于在超类上查找已被 instance 属性遮蔽的 class 属性可能很有用,但如果类和超类都使用相同的实例属性名称(并且不涉及私有名称修改),则两者共享 same 属性,层次结构中不同级别使用的版本之间没有区别。