Calling a parent class constructor from a child class in python [duplicate]

隐身守侯 提交于 2020-05-09 19:04:26

问题


So if I have a class:

 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

And then this subclass:

 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)

I'm a bit lost on how to get the subclass to call and use the parent class constructor for name and year, while adding the new parameter degree in the subclass.


回答1:


Python recommends using super().

Python 2:

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

Python 3:

super().__init__(name, year)


来源:https://stackoverflow.com/questions/12557612/calling-a-parent-class-constructor-from-a-child-class-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!