Python super()
2021/8/27 11:06:10
本文主要是介绍Python super(),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.描述
super() 用于调用父类。
super() 用来解决多重继承,直接用类名调用父类方法在单继承的时候是没有问题,但在多继承上,涉及查找顺序、重复调用等问题。
MRO 是类的方法解析顺序表,其实也是继承父类方法时的顺序表。
2.语法
super(type[, object-or-type])
参数:
type
:类
object-or-type
:类,一般是 self
实例:
class A: def __add__(self, x): y = x+1 print(y) class B(A): def __add__(self, x): super(B, self).__add__(x) b = B() b.__add__(2)
输出:
3
class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print ('Parent') def bar(self,message): print ("%s from Parent" % message) class FooChild(FooParent): def __init__(self): # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象 super(FooChild,self).__init__() print ('Child') def bar(self,message): super(FooChild, self).bar(message) print ('Child bar fuction') print (self.parent) if __name__ == '__main__': fooChild = FooChild() fooChild.bar('HelloWorld')
输出:
Parent Child HelloWorld from Parent Child bar fuction I'm the parent.
这篇关于Python super()的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础
- 2024-09-2610 种方法写出更好的 Python 代码
- 2024-09-25Python编程基础详解
- 2024-09-25Python编程入门教程
- 2024-09-25从零开始使用Python构建LLaMA 3
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战