python - 为什么当我们使用类名调用超类的构造函数时我们传递 self 而使用 super 时却没有
问题描述
正如您可以看到下面提供的代码,我在 python 中使用 OOP 并发现了一些我无法理解的东西。据我所知,我们可以通过使用 super() 或类名本身来调用超类的构造函数,但是如果我在 #001 行中传递 self ,则在 #001 和 #002 行中,它会给我一个错误,如果我这样做不要在 #002 中传递 self 它再次给我一个错误。那么为什么通过这两种方法调用超类的构造函数时传递和不传递self有区别呢?如果有区别,为什么在使用类名的情况下我们还要传递 self ,因为 self 指的是子类的对象,不是吗?
class A:
def __init__(self,a):
self.a = a
print('Printing self from constructor of A:')
print(self)
print('Printing self from constructor of B ends.\n')
def get_a(self):
print('-----------A-------------')
print(self,'\n',self.get_a)
print('-----------A-------------\n')
class B(A):
def __init__(self,a,b):
#001 super().__init__(a)
#002 A.__init__(self,a)
print('Printing self from constructor of B:')
print(self)
print('Printing self from constructor of B ends.\n')
self.b = b
def get_b(self):
#self.get_a works but get_a() doesn't
print('-----------B-------------')
print(self,'\n',self.get_a,'\n')
print(self,'\n',self.get_b)
print('-----------B-------------\n')
a = A(5)
b = B(50,60)
a.get_a()
b.get_a()
b.get_b()
解决方案
推荐阅读
- android - 生命周期活动秒表
- php - Xampp 恢复数据库
- react-native - React Native:使用 react-native-elements 图标返回找不到变量“React”
- google-apps-script - 无法更新 AppScript Gmail 插件
- amazon-web-services - 什么链接联合身份?
- apache-kafka - 更新 camus 中的 kafka 依赖项导致 EtlRecordReader 未读取消息
- java - java - 如何将注释应用于某些方法调用
- docker - 我仍然对 Docker 容器和图像感到困惑
- java - 如何将请求正文作为 JSON 完全发送到我的 API?
- java - EclipseLink 中的@ManyToOne 映射问题