如何在 Python 中從父類建立子類?


在這篇文章中,我們將討論如何在 Python 中從父類建立子類。在繼續之前,讓我們先了解一下什麼是類和父類。

是使用者定義的模板或原型,用於建立物件。類提供了一種將功能和資料捆綁在一起的方法。透過建立新的類,可以實現建立物件型別的新例項的能力。

類的每個例項都可以與其關聯屬性,以保留其狀態。類例項還可以包含由其類定義的方法,用於更改其狀態。

語法

用於類的語法如下:

class NameOfClass:
# Statement

示例

class 關鍵字表示建立類,後跟類名,即以下示例中的“Sports”:

class Sports: pass print ('Class created successfully')

輸出

以上程式碼的輸出如下:

Class created successfully

在 Python 中子類中建立父類物件

super() 函式提供了訪問父類或同級類的方法和屬性的功能。除了允許多重繼承外,super() 函式還返回一個表示父類的物件。

語法

語法如下:

Super()

它返回一個代理物件,該物件反映父類,並且沒有引數。

示例

super() 函式的示例如下:

class Mammal(object): def __init__(self, Mammal_type): print('Animal Type:', Mammal_type) class Reptile(Mammal): def __init__(self): # calling the superclass super().__init__('Reptile') print('Reptiles are cold blooded') snake = Reptile()

輸出

以上程式碼的輸出如下:

Animal Type: Reptile
Reptiles are cold blooded

示例

以下示例解釋了在 python 中使用 super() 函式:

class Laptop(object): def __init__(self, breadth, height): self.breadth = breadth self.height = height self.area = 50 class Games(Laptop): def __init__(self, breadth, height): super(Games, self).__init__(breadth, height)

輸出

以下是以上程式碼的輸出,其中我們可以訪問 Laptop.area:

# Picking up 5 and 9 for breadth and height respectively
>>> x=Games(5,9)
>>> x.area
50

示例

使用 super() 的單一繼承

以 Cat_Family 為例。Cat_Family 包括 Feline、Tigers 和 Lynx。它們也有一些共同的特徵,例如:

  • 它們是趾行。
  • 它們的前腳有五個腳趾,後腳有四個腳趾。
  • 它們無法檢測甜味。

因此,Feline、Tiger 和 Lynx 是 Cat Family 類的子類。由於多個子類從單個父類繼承,因此這是一個單一繼承的示例。

class Cat_Family: # Initializing the constructor def __init__(self): self.digitigrade = True self.ToesOnForefeet = 5 self.ToesOnHindfeet = 4 self.LackSweetTasteReceptor = True def isDigitigrade(self): if self.digitigrade: print("It is digitigrade.") def LackOfSweetnessTste(self): if self.LackSweetTasteReceptor: print("It cannot detect sweetness.") class Feline(Cat_Family): def __init__(self): super().__init__() def isMammal(self): super().isMammal() class Tigers(Cat_Family): def __init__(self): super().__init__() def hasToesOnForefeetAndHindfeet(self): if self.ToesOnForefeet and self.ToesOnHindfeet == 4: print("Has toes on forefeet and hind feet") # Driver code Pet = Feline() Pet.isDigitigrade() Street = Tigers() Street.hasToesOnForefeetAndHindfeet()

輸出

以下是以上程式碼的輸出:

It is digitigrade.
Has toes on forefeet and hind feet

Python super() 方法的應用和限制

Python 中的 Super() 方法有兩個主要應用:

  • 允許我們避免顯式使用基類名稱。
  • 處理多重繼承

super 函式有以下三個限制:

  • super 函式引用的類及其方法
  • 呼叫的函式的引數應與 super 函式的引數匹配。
  • 使用後,super() 必須包含在方法的每個例項中。

更新於:2022-11-23

4K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.