如何在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包括猫科动物、老虎和猞猁。它们也有一些共同的特征,例如:
- 它们是趾行。
- 它们的前脚有五个脚趾,后脚有四个脚趾。
- 它们无法检测甜味。
因此,猫科动物、老虎和猞猁是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()必须包含在方法的每个实例中。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP