【发布时间】:2014-10-28 21:56:52
【问题描述】:
我正在使用 python3.2 并且我有一个继承两个类的类。子类的子类__init__ 函数具有不同的签名。简而言之,是否可以创建一个调用每个子类的__init__ 的Parent 对象?
背景
假设我有以下python3.2代码
class A(object):
def __init__(self, name):
self.ver = "the ver"
print("A::__init__ .... name = %s" % name)
class B(object):
def __init__(self,):
self.name = "the name"
print("B::__init__")
def foo(self,):
print("B::foo. The name is >>%s<<" % self.name)
class C(B,A):
def __init__(self,):
print("C::__init__")
super(B, self).__init__()
super(A, self).__init__('waaa')
我可以创建A 和B 的实例
>>> a = A('myplace')
A::__init__ .... name = myplace
>>> b = B()
B::__init__
但是创建C 的实例失败。
>>> c = C()
C::__init__
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<console>", line 4, in __init__
TypeError: __init__() takes exactly 2 arguments (1 given)
如果我将C的__init__修改为
class C(B,A):
def __init__(self,):
print("C::__init__")
super(B, self).__init__('another')
super(A, self).__init__('waaa')
我在创建C 的实例时得到以下信息
>>> C()
C::__init__
A::__init__ .... name = another
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<console>", line 5, in __init__
TypeError: object.__init__() takes no parameters
>>>
我的问题
我阅读了super()的文档,不清楚是否可以调用每个子类的__init__。
看来super(B, self)__init__('another')实际上是在调用A类的__init__,而super(A, self).__init__('waaa')是在调用B类的__init__。
- 为什么
super()不尊重它的type参数? - 如何创建一个对象
C,它同时具有A和B的所有类属性和方法?
【问题讨论】:
-
super的重点就是你调用一次,所有继承的功能(包括多重继承)都处理好了。这确实意味着调用签名必须匹配(或使用*args和**kwargs来处理差异)。
标签: python oop python-3.x super