为什么需要super
在python没有引入super之前, 如果需要在子类中引用父类的方法, 一般写法如下:
class Father:
def whoami(self):
print("I am father")
class Child:
def whoami(self):
print("I am child")
Father.whoami(self)
这样看好像没什么问题, 就算没有super也能正常调用父类的方法, 但是如果有一天Father类需要修改类名为Father1, 那么子类Child中也必须跟着修改.
想象下如果一个类有很多个子类, 这样一来我们就需要修改每个子类中引用父类的语句
怎么使用super
Help on class super in module builtins: class super(object) | super() -> same as super(__class__, <first argument>) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) | Typical use to call a cooperative superclass method: | class C(B): | def meth(self, arg): | super().meth(arg) | This works for class methods too: | class C(B): | @classmethod | def cmeth(cls, arg): | super().cmeth(arg)
我们来看看super的帮助文档, 首先super是一个类, 它的调用方法有如下几种:
1.super()
2.super(type)
3.super(type, obj)
4.super(type, type2)
我们推荐用第一种方法来使用super, 因为它并不需要显式传递任何参数.但是要注意一点, super只能在新式类中使用.
class A:
def __init__(self):
print("this is A")
class B(A):
def __init__(self):
super().__init__()
print("this is B")
b = B()
"""
this is A
this is B
"""
看起来super就像直接调用了B的父类A的__init__, 其实并不是这样的, 我们看看super在多继承下的使用
class A:
def __init__(self):
print("this is A")
print("leave A")
class B(A):
def __init__(self):
print("this is B")
super().__init__()
print("leave B")
class C(A):
def __init__(self):
print("this is C")
super().__init__()
print("leave C")
class D(B, C):
def __init__(self):
print("this is D")
super().__init__()
print("leave D")
d = D()
"""
this is D
this is B
this is C
this is A
leave A
leave C
leave B
leave D
"""
print(D.__mro__)
"""
(<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.C'>,
<class '__main__.A'>,
<class 'object'>)
"""
这里可以看到, 如果super只是简单调用父类的方法的话, 那么调用了B的__init__ 方法之后, 应该调用A的__init__ 才对, 但是调用的却是C的__init__ 方法
这是因为super调用的是当前类在MRO列表中的后一个类, 而并不是简单地调用当前类的父类
python并没有强制性限制我们使用super调用父类, 我们还是可以使用原始的方法来调用父类中的方法, 但是需要注意的是调用父类的方法要统一, 即全用super或全不用super, 而用super 的话, 调用的方式也最好是统一的
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新动态
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]