如何在继承的类中执行常见的初始化后任务? [英] How to perform common post-initialization tasks in inherited classes?

查看:67
本文介绍了如何在继承的类中执行常见的初始化后任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一组具有共同父代的类的初始化过程可以分为三个部分:

The initialization process of a group of classes that share a common parent can be divided into three parts:

  • 常用初始化
  • 特定于子类的初始化
  • 常见的后初始化

当前,前两个部分是通过每个子类的__init__方法调用的,但是最后的后初始化部分必须分别调用,例如

Currently the first two parts are called from the __init__ method of each child class, but the final post-initialization part has to be called separately, for example

class BaseClass:
    def __init__(self):
        print 'base __init__'
        self.common1()

    def common1(self):
        print 'common 1'

    def finalizeInitialization(self):
        print 'finalizeInitialization [common2]'


class Subclass1(BaseClass):
    def __init__(self):
        BaseClass.__init__(self)
        self.specific()

    def specific(self):
        print 'specific'


if __name__ == '__main__':
    s = Subclass1()  # Don't forget to finalize the initialization
    s.finalizeInitialization()  # now the object is fully initialized

是否有一种不必致电finalizeInitialization()的方法?或者可以将对finalizeInitialization()的呼叫转移到Subclass1__init__中(如

Is there a way to not to have to call finalizeInitialization()? Or one can transfer the call to finalizeInitialization() into Subclass1's __init__ (as in S.Lott's answer). This makes the life easier, but still one has to remember to complete the initialization, this time inside the "constructor". Either way there is no way to enforce full initialization, which is what I'm looking for.

推荐答案

版本1-委托所有内容.

Version 1 - delegate everything.

class Subclass1(BaseClass):
    def __init__(self):
        super( Subclass1, self ).__init__()
        self.specific()
        super( Subclass1, self ).finalizeInitialization()

版本2-仅委派一个步骤

Version 2 - delegate just one step

class BaseClass:
    def __init__(self):
        print 'base __init__'
        self.common1()
        self.specific()
        self.finalizeInitialization()

    def common1(self):
        print 'common 1'

    def finalizeInitialization(self):
        print 'finalizeInitialization [common2]'

    def specific( self ):
        # two choices:
        # if this is "abstract": raise an exception
        # if this is "concrete": pass

这篇关于如何在继承的类中执行常见的初始化后任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆