从python中的子类调用父类构造函数 [英] Calling a parent class constructor from a child class in python

查看:242
本文介绍了从python中的子类调用父类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,如果我有课:

 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的问题.

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.

推荐答案

Python建议使用super().

Python recommends using super().

Python 2:

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

Python 3:

super().__init__(name, year)

这篇关于从python中的子类调用父类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆