Python继承示例
时间:2020-02-23 14:42:49 来源:igfitidea点击:
大家好,以python继承为例。
在上一教程中,我们了解了python运算符重载。
在本教程中,我们将讨论python的另一个重要的面向对象功能,即继承。
Python继承
基本上,几乎所有面向对象的编程语言都包含继承。
Python继承使我们能够将一个类的成员属性和方法用于另一个类。
Python继承术语
超类:将从其继承属性和方法的类。
子类:从超类继承成员的类。
方法重写:重新定义子类中已经在超类中定义的方法的定义。
Python继承范例
现在,让我们使用python继承示例程序。
#Line:1, definition of the superclass starts here
class Person:
#initializing the variables
name = ""
age = 0
#defining constructor
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
#defining class methods
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
#Line: 19, end of superclass definition
#definition of subclass starts here
class Student(Person): #Line: 22, Person is the superclass and Student is the subclass
studentId = ""
def __init__(self, studentName, studentAge, studentId):
Person.__init__(self, studentName, studentAge) #Line: 26, Calling the superclass constructor and sending values of attributes.
self.studentId = studentId
def getId(self):
return self.studentId #returns the value of student id
#end of subclass definition
# Create an object of the superclass
person1 = Person("Richard", 23) #Line: 35
#call member methods of the objects
person1.showAge()
# Create an object of the subclass
student1 = Student("Max", 22, "102") #Line: 39
print(student1.getId())
student1.showName() #Line: 41
现在,我们将解释上面的示例,以了解继承如何在python中工作。
定义超类
第1-19行定义了超类。
如果您熟悉python类,则无需理会。
类" Person"是使用必要的构造函数,属性和方法定义的。
Python类教程中已经提供了此部分的说明。
定义子类
根据继承规则,子类继承其超类的属性和方法。
第22行显示了子类Student如何将Person扩展为其超类。
在声明子类时,必须在括号中保留超类的名称。
并且构造函数必须使用适当的属性值(如果需要)调用超类构造函数,如第26行所示。
除此之外,一切都与定义普通的python类相同。
在定义了超类和子类之后,我们可以像第35和39行中那样创建超类和子类的对象。
正如我们前面所讲的,子类继承了属性和方法。
您可能在这里注意到,对象student1(Student子类的对象)在其作用域内(第41行)具有showName方法。

