大家好,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
is defined with necessary constructor, attributes and methods. Explanation of this segment has already been provided in Python类辅导的。
定义子类
根据继承规则,子类继承其父类的属性和方法。第22行显示了子类Student如何将Person扩展为其父类。在声明子类时,父类的名称必须放在括号中。构造函数必须使用适当的属性值(如果需要)调用父类构造函数,如第26行所示。除此之外,一切都与定义一个普通的python类是一样的。
在定义了父类和子类之后,我们可以创建父类和子类的对象,如第35行和第39行所示。如前所述,子类继承属性和方法。您可能会注意到对象student1(Student子类的对象)在其作用域(第41行)下有一个showName方法。
在python编译器上运行后,代码将生成以下输出。
所以,这是python继承的基础。我们将在多重继承一节中了解更多关于继承的内容。编码快乐,再见!
您可以从我们的GitHub存储库.
参考文献:Python.org网站医生.