python子类构造函数

lad*_*afa 2 python initialization

在python OOP中,让我们说,Person是一个具有自己的构造函数的父类; 那么Student是Person的子类,在我使用Student之前,必须Person.__init__(self)先在Student的构造函数中调用它?另外,我可以在Student类中定义一个新的构造函数吗?

class Person():      
    def __init__(self):  
Run Code Online (Sandbox Code Playgroud)

上面是类Person及其构造函数

class Student(Person):    
    def __init__(self):  
        Person.__init__(self)   
    def __init__(self, age)
Run Code Online (Sandbox Code Playgroud)

我的意思是,学生可以拥有自己的构造函数吗?如果是这样,Person.__init__(self)在这种情况下必须在Student构造函数中调用?

sat*_*oru 8

当然,Student可以拥有自己的构造函数.但是,一个类在Python中只能有一个构造函数,没有什么比构造函数重载更好.

所以当我们说子类有自己的构造函数时,我们的意思是这样的:

class Worker(People):
    def __init__(self, company):
        self.company = company
Run Code Online (Sandbox Code Playgroud)

正如@IanH指出的那样,你不必调用超类构造函数.当你认为你应该调用它时(可能是为了一些常见的初始化),你可以这样做:

class People:
    def __init__(self, name):
        self.name = name

class Student(People):
    def __init__(self, name, school):
        super(Student, self).__init__(name)
        self.school = school
Run Code Online (Sandbox Code Playgroud)