Python继承
Python继承
继承允许我们定义一个类,该类从另一个类继承所有方法和属性。
父类是从其继承的类,也称为基类。
子类是从另一个类(也称为派生类)继承的类。
创建一个家长班
任何类都可以是父类,因此语法与创建任何其他类相同:
例
Person
使用
firstname
和lastname
属性创建一个名为的类以及一个printname
方法:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname,
self.lastname)
#Use the Person class to create an object, and then
execute the printname method:
x = Person("John", "Doe")
x.printname()
自己尝试»
创建一个子班
要创建一个从另一个类继承功能的类,请在创建子类时将父类作为参数发送:
例
创建一个名为的类Student
,该类将从该类继承属性和方法Person
:
class Student(Person):
pass
注意:pass
当您不想向该类添加任何其他属性或方法时,请使用关键字。
现在,Student类具有与Person类相同的属性和方法。
添加__init __()函数
到目前为止,我们已经创建了一个子类,该子类从其父类继承属性和方法。
我们希望将__init__()
功能添加到子类(而不是pass
关键字)。
注意:__init__()
每次使用该类创建新对象时,都会自动调用该函数。
例
将__init__()
函数添加到
Student
类中:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
当您添加__init__()
函数时,子类将不再继承父__init__()
函数。
注意:子级__init__()
函数将覆盖父级
__init__()
函数的继承。
要保留父__init__()
函数的继承,请添加对父函数的调用__init__()
:
例
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
自己尝试»
现在,我们已经成功添加了__init __()函数,并保留了父类的继承,并且我们准备在该__init__()
函数中添加
功能。
使用super()函数
Python还有一个super()
函数可以使子类从其父类继承所有方法和属性:
通过使用该super()
函数,您不必使用父元素的名称,它将自动从其父元素继承方法和属性。
添加属性
例
graduationyear
在
Student
类中添加一个名为的属性:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear
= 2019
自己尝试»
在下面的示例中,年份2019
应为变量,并Student
在创建学生对象时传递给
班级。为此,在__init __()函数中添加另一个参数:
例
添加一个year
参数,并在创建对象时传递正确的年份:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear
= year
x = Student("Mike", "Olsen", 2019)
自己尝试»
新增方法
例
welcome
在
Student
类中添加一个方法:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear
= year
def welcome(self):
print("Welcome",
self.firstname, self.lastname, "to the class of", self.graduationyear)
自己尝试»
如果在子类中添加与父类中的函数同名的方法,则父方法的继承将被覆盖。