【问题标题】:Calling a parent class constructor from a child class in python [duplicate]从python中的子类调用父类构造函数[重复]
【发布时间】:2012-09-15 11:23:49
【问题描述】:

如果我有课:

 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,我有点迷茫。

【问题讨论】:

  • 你有什么问题?
  • 你做的应该没问题...
  • 哦,好吧,我不确定,也想不出测试它的方法……我发现我一直都是正确的……我很抱歉。

标签: python inheritance


【解决方案1】:

Python 建议使用super()

Python 2:

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

Python 3:

super().__init__(name, year)

【讨论】:

  • 我在使用超级 init 方法时遇到的唯一问题是,它没有返回父类的实例。因此,如果根据父 init 方法中的名称和年份推断出第三个参数,则子对象无法访问该第三个参数,因为__init__ 不会返回它。所以我更喜欢从 Instructor 那里调用 Person(name, year)
  • 没有“父类的实例”。只有一个实例,就是正在初始化的那个,通常称为“self”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多