title: python之super()函數的用法
date: 2018-12-22 21:56:23
categories: python
tags:
- pythontags:
描述
super() 函數是用於調用父類(超類)的一個方法。
super 是用來解決多重繼承問題的,直接用類名調用父類方法在使用單繼承的時候沒問題,但是如果使用多繼承,會涉及到查找順序(MRO)、重複調用(鑽石繼承)等種種問題。
MRO 就是類的方法解析順序表, 其實也就是繼承父類方法時的順序表。
語法
以下是super()方法的語法
super(type[,object-or-type])
參數
type --- 類
object-or-type --- 類,一般是self
Python3.x 和 Python2.x 的一個區別是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :
Python3.x 實例:
class A:
pass
class B(A):
def add(self,x):
super().add(x)
Python2.x 實例:
class A(object): # Python2.x 記得繼承 object
pass
class B(A):
def add(self, x):
super(B, self).add(x)
實例
class FooParent(object):
def __init__(self):
self.parent='I am the parent.'
print ('parent')
def bar(self,message):
print("%s from Parent" %message)
class FooChild(FooParent):
def __init__(self):
# super(FooChild,self) 首先找到 FooChild 的父類(就是類 FooParent),然後把類B的對象 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('hello,world')