【问题标题】:What happens when __init__() gets some arguments [duplicate]当 __init__() 得到一些参数时会发生什么[重复]
【发布时间】:2014-05-08 18:34:21
【问题描述】:

super(SomeClass, self).__init__()super(SomeClass, self).__init__(*args, **kwargs) 有什么区别?第一个初始化父级的构造函数,但是第二个呢?

【问题讨论】:

  • 这个问题不断出现。答案每次都是一样的,你会被*args**kwargs 语法所困扰,而不是__init__ 方法。
  • @MartijnPieters 感谢您的评论。我实际上知道那些 STARS,而且我已经说过了。我不是专业程序员,但这并不意味着我太愚蠢而不能一次又一次地问同样的问题。看看我选出的最佳答案,它清楚地回答了我的问题。

标签: python oop init


【解决方案1】:

第二个调用超类的构造函数带参数

一些演示:

>>> 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)

【讨论】:

    【解决方案2】:

    super(SomeClass, self) 返回一个代表某个类的代理对象(不一定是SomeClass 的父对象,如果涉及多重继承)。因此,您需要将适当的参数传递给它的__init__ 方法。如果它需要参数,第一个将失败。如果它不需要任何参数,那么第二个可能失败,如果 argskwargs 还不是空的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多