python __init__ method in inherited class

前端 未结 6 1823
深忆病人
深忆病人 2021-02-07 01:36

I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__

6条回答
  •  死守一世寂寞
    2021-02-07 02:07

    Just call a designated method from the parent's init, if it exists:

    class initialclass():
        def __init__(self):
            self.attr1 = 'one'
            self.attr2 = 'two'  
            if hasattr(self, 'init_subclass'):
                self.init_subclass()
    
    class inheritedclass(initialclass):
        def init_subclass(self):
            self.attr3 = 'three'
    

提交回复
热议问题