【问题标题】:extending an overloaded class __init__ and making the child classes __init__ compatible with the overloaded class?扩展重载类 __init__ 并使子类 __init__ 与重载类兼容?
【发布时间】:2015-03-03 16:17:21
【问题描述】:

假设 A 类有一个重载的 init?在需要多个参数集的情况下,如何首先重载 init

另外,当扩展到子类时,如何确保子 init 与重载的父 init 兼容?

【问题讨论】:

  • 请考虑使用一些示例代码来说明您要问的问题,让这个问题更清楚。

标签: python class overloading init


【解决方案1】:

Python 不支持函数重载,因为它是一种动态语言,请参阅: Overloaded functions in python?

如果我理解正确,您需要super 从您的子类调用您的基类的方法:

In [95]: class Base(object):
    ...:     def __init__(self, x):
    ...:         print 'in Base.ctor, x is:', x
    ...: 
    ...: class Child(Base):
    ...:     def __init__(self, x, y):
    ...:         super(Child, self).__init__(x)

In [96]: c = Child(1,2)
in Base.ctor, x is: 1

见:Understanding Python super() with __init__() methods

【讨论】:

  • 如果继承继续,super(self.__class__, self) 会被破坏——试试class Grandchild(Child): pass 看看实例化 if 会发生什么。在 Python 2 中,您需要在 super 中显式,在这种情况下使用 super(Child, self)
猜你喜欢
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 2010-09-13
  • 2011-08-07
  • 1970-01-01
相关资源
最近更新 更多