您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

简短的答案是object .()方法不执行任何操作,只是检查是否已传入任何参数。有关详细信息,请参见

Service 实例上调用时,super() 调用将委派给object .(),并且不会发生任何事情。

但是,当调用 Service 子类的实例时,事情会变得更加有趣。该 超() 调用有可能委托给一些类以外 的对象 ,一类是实例的父但不是家长服务 。有关它如何工作以及为什么有用的详细信息,请参阅博客文章Python的“超级被认为是超级”

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

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

在示例中,初始化按以下顺序进行:

python 2022/1/1 18:28:29 有198人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶