Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

35. Python 继承

大家好,python继承示例。在上一个教程中,我们了解到python运算符重载. 在本教程中,我们将讨论python另一个重要的面向对象特性,即继承。

Python继承

基本上,几乎所有面向对象编程语言都包含继承。Python继承使我们能够将一个类的成员属性和方法用于另一个类。

Python继承术语

  1. 父类:将从中继承属性和方法的类。
  2. 子类:继承自父类的成员。
  3. 方法重写:重新定义子类中已在父类中定义的方法的定义。

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网站医生.