扩展重载类__init__并使子类__init__与重载类兼容?

时间:2015-01-06 02:25:44

标签: python class overloading init

假设A类有一个超载的 init ?如何在第一个地方重载 init ,它需要设置多于1个参数?

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

1 个答案:

答案 0 :(得分:0)

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