如何在 Python 中从父类创建子类?
在这篇文章中,我们将讨论如何在 Python 中从父类创建子类。在继续之前,让我们先了解一下什么是类和父类。
类是用户定义的模板或原型,用于创建对象。类提供了一种将功能和数据捆绑在一起的方法。通过创建新的类,可以实现创建对象类型的新实例的能力。
类的每个实例都可以与其关联属性,以保留其状态。类实例还可以包含由其类定义的方法,用于更改其状态。
语法
用于类的语法如下:
class NameOfClass: # Statement
示例
class 关键字表示创建类,后跟类名,即以下示例中的“Sports”:
class Sports: pass print ('Class created successfully')
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
以上代码的输出如下:
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() 必须包含在方法的每个实例中。