python类的继承
现有父类:
class Person:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def print():
print(self.firstname, self.lastname)
子类可直接继承:
class Student(Person):
pass
也可在子类中添加__init__函数,一旦添加,子类中的init就会覆盖父类中的init。
但如果在子类中添加了init又想继承父类init,可以在子类的init中添加对父类init的调用:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
初始化方法继承父类的属性后,可以继续在初始化函数内添加新的属性,在其外续写新的函数。
super函数也可以使子类继承父类中所有属性及方法,使用super时可以不必使用父类的名称:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
注意super后有括号,且函数后的形参中没有self。
python类的继承
http://example.com/2023/02/07/2.7 python类的继承/