object的__init __()方法在python中做了什么?

can*_*an. 21 python object init

在阅读OpenStack的代码时我遇到了这个问题.

名为"Service"的类继承基类"object",然后在Service的__init__()方法__init__中调用object .相关代码如下所示:

类定义:

class Service(object):
Run Code Online (Sandbox Code Playgroud)

和服务的init方法定义:

def __init__(self, host, binary, topic, manager, report_interval=None,
             periodic_interval=None, *args, **kwargs):
Run Code Online (Sandbox Code Playgroud)

并在Service的init中调用super(这里的'object'):

super(Service, self).__init__(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

我不明白最后一次电话,object.__init__()它实际上做了什么?有人可以帮忙吗?

Ray*_*ger 14

简短的回答是object .__ init __()方法除了检查没有传入任何参数外什么都不做.有关详细信息,请参阅源代码.

当调用Service实例时,super()调用将委托给object .__ init __(),什么都不会发生.

但是,当调用Service的子类的实例时,事情变得更有趣.该超()调用有可能委托给一些类以外的对象,一类是实例的父但不是家长服务.有关其工作原理及其有用的详细信息,请参阅Python的Super Considered Super博客文章!

下面的例子(有点做作)显示的子类,如何服务可能会导致超级呼叫服务被定向到另一个名为类颜色:

class Service(object):
    def __init__(self, host, binary, topic, manager, report_interval=None,
             periodic_interval=None, *args, **kwargs):
        print 'Initializing Service'
        super(Service, self).__init__(*args, **kwargs)

class Color(object):
    def __init__(self, color='red', **kwargs):
        print 'Initializing Color'
        self.color = color
        super(Color, self).__init__(**kwargs)

class ColoredService(Service, Color):
    def __init__(self, *args, **kwds):
        print 'Initializing Colored Service'
        super(ColoredService, self).__init__(*args, **kwds)

c = ColoredService('host', 'bin', 'top', 'mgr', 'ivl', color='blue')
Run Code Online (Sandbox Code Playgroud)

在该示例中,初始化按以下顺序发生:

  1. 初始化有色服务
  2. 初始化服务
  3. 初始化颜色
  4. 初始化对象 - 除了参数检查之外什么也不做

  • 参考文献[Python的Super Considered Super](http://rhettinger.wordpress.com/2011/05/26/super-considered-super/)有很多帮助.谢谢! (2认同)