直接看代码:
class Person:
def __init__(self):
self.name = "jack"
class Student(Person):
def __init__(self):
self.school = "一中"
stu = Student()
print("学生的姓名是:",stu.name)
此时,程序是不能正常运行的,运行之后报错:
这是为什么呢?
__init__相当于是python类的构造方法,在类进行实例化时被调用,当子类和父类中都存在构造方法时,子类中需要显示调用父类的构造方法 。需要注意的是python中构造方法是不能进行重载的,当有多个构造方法存在时,会默认调用最后一个构造方法。修改后的代码如下:
class Person:
def __init__(self):
self.name = "jack"
class Student(Person):
def __init__(self):
super(Student, self).__init__()
self.school = "一中"
stu = Student()