python - 为什么 Python 中的 Super() 不采用子类中的父类实例变量
问题描述
我是 Python 中 OOP 的新手,我试图通过使用超级方法“super()”来访问实例方法的实例变量,并且我尝试了多种可能性,但我发现每当我使用访问实例变量时,我都是获取属性错误
我的代码
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() 方法不能使内部系统访问实例变量?
解决方案
那是因为super().m1()
是相同的功能self.m1()
意味着它将属性b
设置为类C
class P:
def m1(self):
self.b=10
class C(P):
def __init__(self):
super().m1()
print(self.b)
c=C()
这将打印10
推荐阅读
- java - git clone 在 docker 文件中不起作用
- python - 创建另一个数据集的列之间差异的新数据集
- c# - 在 aspnet core 2.1 中生成 Swashbuckle 实现笔记
- python - 如何使用 python 从 XML 文件中仅解析和获取所需的 XML 元素?
- asp.net - JS 文件不会出现在 Scripts 文件夹中
- java - @Transactional 在带有自定义事务管理器的 Spring Boot 中不起作用
- android - onTaskRemoved() 不适用于 Android 8.0 Oreo API 级别 26
- angular - 在角度 CLI 中出现构建错误:无法重新声明块范围变量“ngDevMode”
- android - 使用 Volley 无法正确执行 HTTP GET?
- c# - 如何以 json 格式编写特定的 C# 属性值?