1. 程式人生 > >Python內置函數之super()

Python內置函數之super()

方式 () super 繼承類 pan 調用 一個 我們 更改

super(type[,object-or-type])

super()的作用在於類繼承方面。

他可以實現不更改類內部代碼,但是改變類的父類。

例子:

一般我們繼承類的方式:
>>> class A:
...   def __init__(self):
...     print(A.__init__)
...
>>> class B(A):
...   def __init__(self):
...     print(B.__init__)
...     A.__init__(self)
...
>>> b = B()
<function B.__init__ at 0x000000E8A87DC840
> <function A.__init__ at 0x000000E8A87DC9D8> 這樣有一個問題,當B的父類換為A1時,又要去修改B類內部的值,這樣做很不方便! 於是有了super()這樣的替代方式: >>> class B(A): ... def __init__(self): ... print(B.__init__) ... super().__init__() #等效於super(B,self).__init__() ... >>> b = B() <function B.__init__ at 0x000000E8A87DC7B8
> <function A.__init__ at 0x000000E8A87DC9D8> 這樣的方式避免了修改B類的內部,便於維護了。 如果只有一個參數,則不會繼承父類。#super(B).__init__(),只會調用B類本身 如果第二個參數是一個類對象,那麽該類對象是第一個參數的子類。

Python內置函數之super()