目录
1 super( ) 的用途
了解 super() 函数之前,我们首先要知道 super() 的用途是啥?
- 主要用来在子类中调用父类的方法。
- 多用于多继承问题中,解决查找顺序(MRO)、重复调用(钻石继承)等种种问题。
2 了解 super 的基础信息
语法格式:
super([type[, object-or-type]])
函数描述:
- 返回一个代理对象,它会将方法调用委托给 type 的父类或兄弟类。
参数说明:
- type —— 类,可选参数。
- object-or-type —— 对象或类,一般是 self,可选参数。
返回值:
- super object —— 代理对象。
help 帮助信息:
>>> help(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 是一个继承自 object 的类,调用 super() 函数其实就是 super 类的实例化。
- 根据官方文档的解释 super() 函数返回的对象 —— super object,就是一个代理对象。
- super() 有四种参数的组合形式。
- super() 适用于类的静态方法。
3 典型用法
3.1 单继承问题
首先我们看一个最基本的子类调用父类方法的示例: