super方法 調用父類的方法


描述

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 實例:

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)

返回值

無。

注意:

注意:super繼承只能用於新式類,用於經典類時就會報錯。
新式類:必須有繼承的類,如果沒什么想繼承的,那就繼承object
經典類:沒有父類,如果此時調用super就會出現錯誤:『super() argument 1 must be type, not classobj』

實例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
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上面如self.umn =umn
        # 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('HelloWorld')

    # Parent
    # Child
    # HelloWorld
    # from Parent
    # 
    # Child
    # bar
    # fuction
    # I
    # 'm the parent.

更加清楚的看:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

class FooParent():
    def __init__(self):
        self.parent = 'I\'m the 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__()
    def bar(self, message):
        super(FooChild, self).bar(message)
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')
#返回結果
#HelloWorld from Parent


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM