关于继承:从Python中的子类调用父类构造函数

Calling a parent class constructor from a child class in python

本问题已经有最佳答案,请猛点这里访问。

所以如果我有课:

1
2
3
4
5
6
7
 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

然后这个子类:

1
2
3
4
 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有点迷茫。


python建议使用super()

Python 2:

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

Python 3:

1
super().__init__(name, year)