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()
运行实例 »
创建子类
要创建从其他类继承功能的类,请在创建子类时将父类作为参数传递:class Student(Person): pass
注意:
Student类继承Person类相同的属性和方法。
pass 如果您不想向该类添加任何其他属性或方法,请使用该关键字。
添加__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__()功能。
添加属性
实例
在Student类中添加名为graduationyear属性 :class Student(Person): def __init__(self, fname, lname): Person.__init__(self, fname, lname) self.graduationyear = 2019运行实例 »
Student对像时传递到类中。因此,请在__init __()函数中添加新的参数:
实例
添加year参数,并在创建对象时传递正确的年份:
class Student(Person):
def __init__(self, fname, lname, year):
Person.__init__(self, fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
运行实例 »
添加方法
实例
在Student类中添加一个 welcome 方法:
class Student(Person):
def __init__(self, fname, lname, year):
Person.__init__(self, fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
运行实例 »
