Skip to main content
 首页 » 编程设计

python之继承时避免 __init__ 和 super 样板

2025年01月19日12cmt

假设我有以下类(class):

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

请您参考如下方法:

如果子类中不需要具体的初始化,可以省略__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