继承时避免使用__init__和超级样板

时间:2017-11-13 16:29:47

标签: python python-3.x oop inheritance

说我有以下课程:

class Base(object):

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):

    # the method I would like to avoid
    def __init__(self, **kwargs):
        super(Child, self).__init__(**kwargs)

有没有办法避免在Child类中调用__init__super的样板?在这个包中,用户会经常从基类继承,但我希望每次都使用__init__super来避免它们,特别是因为模式永远不会改变。但是它仍然需要接受关键字参数。

我想这可能是使用__new__或元类,但必须有一个更简单的方法在基类中使用@classmethod之类的东西?

编辑:使用python3

1 个答案:

答案 0 :(得分:1)

如果您不需要在子类中进行特定初始化,则可以省略__init__

class Base:

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):
    pass

否则,你应该这样使用它:

class Base(object):

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        #...additional specific initialization
相关问题