Python - 继承
时间:2020-02-23 14:42:49 来源:igfitidea点击:
在本教程中,我们将学习Python的继承。
什么是继承?
继承是OOP的核心概念之一-面向对象编程。
它有助于我们创建层次结构。
继承是子类从父类继承属性和方法的概念。
超类和子类
用于创建其他类的类称为父类或者超类。
继承父类的属性和方法的类称为子类或者子类。
Python中的继承
以下是Python中继承的语法。
# parent class class ParentClass: # # some attributes of the parent class # # # some methods of the parent class # class ChildClass(ParentClass): # # some attributes of the child class # # # some methods of the child class #
注意! " ParentClass"的属性和方法由" ChildClass"继承。
继承实例
在下面的Python程序中,我们有一个父类Employee和一个子类Manager。
# parent class class Employee: def __init__(self, id, name): print("Hello from Employee.__init__()") self.id = id self.name = name def employeeDetail(self): print("ID: %s" %self.id) print("Name: %s" %self.name) # child class class Manager(Employee): def __init__(self, id, name, project): super().__init__(id, name) print("Hello from Manager.__init__()") self.project = project def projectDetail(self): print("Project: %s" %self.project) # object of Manager class obj = Manager(1, 'Jane Doe', 'Android App') # output print("-----Manager Detail-----") obj.employeeDetail() print("-----Project Detail-----") obj.projectDetail()
上面的代码将打印以下输出。
Hello from Employee.__init__() Hello from Manager.__init__() -----Manager Detail---- ID: 1 Name: Jane Doe -----Project Detail---- Project: Android App
说明:
我们有父类" Employee"和子类" Manager",它们继承了父类的属性和方法。
Employee类
在这个类中,我们有一个__init__方法,它使用我们要使用关键字self来保存的雇员的两个参数id和name。
然后,我们有一个" employeeDetail"方法来打印雇员的详细信息。
Manager类
此类还包含__init__方法,它采用雇员的三个参数id
,name
和project
。
在子类中使用" super"方法,我们调用父类的" init"方法。
在Manager类的__init__方法内部,我们调用Employee类的__init__方法,并传递id和name值。
我们使用关键字" self"将" project"的值分配给实例属性" project"。
然后,有一个projectDetail
方法可以打印出项目名称。
创建对象
我们创建一个Manager
类的对象,该对象继承了Employee
类的所有属性和方法。
在实例化Manager类的对象时,我们传递了员工的ID,名称和项目名称。
最后,我们调用了" employeeDetail"和" projectDetail"方法,它们会打印为员工设置的值。