从python中的子类调用父类构造函数

时间:2012-09-24 00:54:52

标签: python inheritance

所以,如果我有一个班级:

 class Person(object):
'''A class with several methods that revolve around a person's Name and Age.'''

    def __init__(self, name = 'Jane Doe', year = 2012):
        '''The default constructor for the Person class.'''
        self.n = name
        self.y = year

然后是这个子类:

 class Instructor(Person):
'''A subclass of the Person class, overloads the constructor with a new parameter.'''
     def __init__(self, name, year, degree):
         Person.__init__(self, name, year)

我有点迷失了如何让子类调用并使用nameyear的父类构造函数,同时在子类中添加新参数degree

1 个答案:

答案 0 :(得分:64)

Python建议使用super()

Python 2:

super(Instructor, self).__init__(name, year)

Python 3:

super().__init__(name, year)