1. 程式人生 > 其它 >Python super().__init__()測試及理解

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

1、

https://blog.csdn.net/qq_38787214/article/details/87902291?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control

2、https://www.runoob.com/w3cnote/python-super-detail-intro.html

3、

Python 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__()的作用也就顯而易見了,就是執行父類的建構函式,使得我們能夠呼叫父類的屬性。

上面是單繼承情況,我們也會遇到多繼承情況,用法類似,但是相比另一種Root.__init__(self),在繼承時會跳過重複繼承,節省了資源。

還有很多關於super的用法可以參考
super的使用
————————————————
版權宣告:本文為CSDN博主「紅鯉魚與彩虹」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/qq_38787214/article/details/87902291

2、