python中def __init__是什么_对象的__init __()方法在python中做什么?

While reading the code of OpenStack and I encountered this.

A class named 'Service' inherits the base class 'object', and then in Service's __init__() method, object's __init__ is called. The related code looks like this:

the class definition:

class Service(object):

and Service's init method definition:

def __init__(self, host, binary, topic, manager, report_interval=None,

periodic_interval=None, *args, **kwargs):

and a call to super(the 'object' here) in Service's init:

super(Service, self).__init__(*args, **kwargs)

I don't understand last call, object.__init__() what does it actually do?

can anyone help?

解决方案

The short answer is that object.__init__() method does nothing except check that no arguments have been passed in. See the source for details.

When called on an instance of Service, the

However, when called on an instance of a subclass of Service, things get more interesting. The super() call can potentially delegate to some class other than object, a class that is a parent of the instance but not a parent of Service. For details on how this works and why it is useful, see the blog post Python's Super Considered Super!

The following example (somewhat contrived) shows how a subclass of Service can cause the super call in Service to be directed to another class called Color:

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

In the example, initializations occur in the following order:

Initializing Colored Service

Initializing Service

Initializing Color

Initialize object -- doing nothing except argument checking

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值