Pyhon的繼承

KaoPuNotes發表於2024-12-10

1 繼承中的__init__初始化函式

1.1 子類沒有定義自己的初始化函式,父類的初始化函式會被預設呼叫:

#定義父類:Parent
class Parent(object):
    def __init__(self, name):
        self.name = name
        print("create an instance of:", self.__class__.__name__)
        print("name attribute is:", self.name)
#定義子類Child ,繼承父類Parent       
class Child(Parent):
    pass
#子類例項化時,由於子類沒有初始化,此時父類的初始化函式就會預設被呼叫
#且必須傳入父類的引數name
c = Child("init Child") 

# 輸出
# create an instance of: Child
# name attribute is: init Child

子類例項化時,由於子類沒有初始化,此時父類的初始化函式就會預設被呼叫
且必須傳入父類的引數name,不傳入會報錯

1.2 子類定義了自己的初始化函式,而在子類中沒有顯示呼叫父類的初始化函式,則父類的屬性不會被初始化

class Parent(object):
    def __init__(self, name):
        self.name = name
        print("create an instance of:", self.__class__.__name__)
        print("name attribute is:", self.name)
    
    def show(self):
        print("this is a method in Parent class")
        print("name attribute is:", self.name)

#子類繼承父類        
class Child(Parent):
    #子類中沒有顯示呼叫父類的初始化函式
    def __init__(self):
        print("call __init__ from Child class")

# c = Child("init Child")  # 報錯
#print()  
#將子類例項化  
c = Child()
# 輸出 call __init__ from Child class
c.show()
# 報錯,因為呼叫了 name 變數
# print(c.name)

這種情況下,子類重寫了init初始化函式,可以呼叫父類的函式,但是父類中所有的變數都無效。

1.3 如果子類定義了自己的初始化函式,顯示呼叫父類,子類和父類的屬性都會被初始化

class Parent(object):
    def __init__(self, name):
        self.name = name
        print("create an instance of:", self.__class__.__name__)
        print("name attribute is:", self.name)

class Child(Parent):
    def __init__(self):
        print("call __init__ from Child class")
        super(Child,self).__init__("data from Child")   #要將子類Child和self傳遞進去
# c = Child("init Child") 
# print() 
# d = Parent('tom')   
c = Child()
print(c.name)

# 輸出
# call __init__ from Child class
# create an instance of: Child
# name attribute is: data from Child
# data from Child

這裡的super函式表示呼叫Child所繼承的父類的初始化函式

References

  • https://blog.csdn.net/brucewong0516/article/details/79121179
  • https://zhuanlan.zhihu.com/p/30239694
  • https://blog.csdn.net/wo198711203217/article/details/84097274

相關文章