super(SomeClass, self).__init__()
和super(SomeClass, self).__init__(*args, **kwargs)
之间有什么区别?第一个初始化父项的构造函数,但是第二个的构造函数呢?
答案 0 :(得分:3)
第二个用参数调用超类'构造函数。
一些示范:
>>> class Base(object):
... def __init__(self, arg1, arg2, karg1=None, karg2=None):
... print arg1, arg2, karg1, karg2
...
>>> b = Base(1, 2, karg2='a')
1 2 None a
>>> class Derived(Base):
... def __init__(self, *args, **kwargs):
... super(Derived, self).__init__(*args, **kwargs)
...
>>> d = Derived(1, 2, karg1='Hello, world!')
1 2 Hello, world! None
>>> class Derived2(Base):
... def __init__(self):
... super(Derived2, self).__init__() # this will fail because Base.__init__ does not have a no-argument signature
...
>>> d2 = Derived2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: __init__() takes at least 3 arguments (1 given)
答案 1 :(得分:1)
super(SomeClass, self)
返回代表某个类的代理对象(不必然是SomeClass
的父代,如果涉及多个继承)。因此,您需要将适当的参数传递给其__init__
方法。如果它期望参数,第一个将失败。如果它没有参数,那么第二个可能失败,如果args
和kwargs
已经空了。