【发布时间】:2021-08-28 15:00:28
【问题描述】:
我是 OOP 的新手 在 Python 中,我试图通过使用超级方法“super()”来访问实例方法的实例变量,并且我尝试了多种可能性,但我发现每当我使用访问实例时变量我得到 AttributeError
我的代码
class P:
def m1(self):
self.b=10
class C(P):
def __init__(self):
super().m1()
print(super().b)
c=C()
class P:
a=888
def m1(self):
self.a=10
**输出:**
Traceback (most recent call last):
File "D:\myPractice.py\sideRun.py", line 9, in <module>
c=C()
File "D:\myPractice.py\sideRun.py", line 7, in __init__
print(super().b)
AttributeError: 'super' object has no attribute 'b'
-----------------------------------------------------------
但是每当我尝试使用 self 访问 Instance 变量时,我都会得到我想要的输出。
我的代码
class C(P):
def __init__(self):
super().m1()
print(super().a)
print(self.a)
c=C()
输出
888
10
我的问题:
为什么 super() 方法不允许内部系统访问实例变量?
【问题讨论】:
标签: python python-3.x class object oop