Python3 super().__init__()測試及理解

Python3 super().__init__()含義

測試一、我們嘗試下面代碼,沒有super(A, self).__init__()時調用A的父類Root的屬性方法(方法裏不對Root數據進行二次操作)

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		#調用屬性

下面是結果:

Traceback (most recent call last):
實例化時執行
這是方法
  File "/hom/PycharmProjects/untitled/super.py", line 17, in <module>
    test.x  # 調用屬性
AttributeError: 'A' object has no attribute 'x'

可以看到此時父類的方法繼承成功,可以使用,但是父類的屬性卻未繼承,並不能用

測試二、我們嘗試下面代碼,沒有super(A,self).__init__()時調用A的父類Root的屬性方法(方法裏Root數據進行二次操作)

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		#調用屬性

結果如下

Traceback (most recent call last):
  File "/home/PycharmProjects/untitled/super.py", line 16, in <module>
    test.fun()  # 調用方法
  File "/home/PycharmProjects/untitled/super.py", line 6, in fun
    print(self.x)
AttributeError: 'A' object has no attribute 'x'

可以看到此時報錯和測試一相似,果然,還是不能用父類的屬性

測試三、我們嘗試下面代碼,加入super(A, self).__init__()時調用A的父類Root的屬性方法(方法裏Root數據進行二次操作)

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__()的作用也就顯而易見了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章