1. 程式人生 > 其它 >python, super().__init__() 起到什麼作用?

python, super().__init__() 起到什麼作用?

技術標籤:python

這裡寫目錄標題

方案一,子類()繼承父類()做了初始化,且不呼叫super初始化父類建構函式,那麼子類(_Init)不會自動繼承父類的屬性()。

class Root(object):
    def __init__(self):
        self.x = '這是屬性'

    def fun(self):
        
        print('這是方法')


class A(Root):
    def __init__(self):
        print('例項化時執行')


test = A()  # 例項化類
test.fun()  # 呼叫方法
test.x  # 呼叫屬性 #此時報錯,不能直接呼叫父類的屬性

執行

在這裡插入圖片描述

方案二

class Root(object):
    def __init__(self):
        self.x= '這是屬性'

    def fun(self):
    	print(self.x)  #此處報錯,不能這樣呼叫父類的屬性
        print('這是方法')
        
class A(Root):
    def __init__(self):
        print('例項化時執行')

test = A()		#例項化類
test.fun()	#呼叫方法
test.x		#呼叫屬性

執行

在這裡插入圖片描述

方案三,如果子類()繼承父類()做了初始化,且呼叫了super初始化了父類的建構函式,那麼子類()也會繼承父類的()屬性。

class Root(object):
    def __init__(self):
        self.x = '這是屬性'

    def fun(self):
        print(self.x)
        print('這是方法')


class A(Root):
    def __init__(self):
        super(A,self).__init__()
        print('例項化時執行')


test = A()  # 例項化類
test.fun()  # 呼叫方法
test.x  # 呼叫屬性


執行

在這裡插入圖片描述
此時A已經成功繼承了父類的屬性,所以super().init

()的作用就是執行父類的__init__函式,使得我們能夠呼叫父類的屬性。

方案4,如果子類()繼承父類()不做初始化,那麼會自動繼承父類()屬性x。

class Root(object):
    def __init__(self):
        self.x = '這是屬性'

    def fun(self):
        print(self.x)
        print('這是方法')

class A(Root):
    print('例項化時執行')


test = A()  # 例項化類
test.fun()  # 呼叫方法
test.x  # 呼叫屬性

執行結果:
例項化時執行
這是屬性
這是方法