python __init__ method in inherited class

前端 未结 6 1830
深忆病人
深忆病人 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:03

    It's incredibly simple. Define a new __init__ method and call the parent's __init__ at the beginning.

    # assuming a class Base, its __init__ takes one parameter x
    
    class Derived(Base):
        def __init__(self, x, y):
            # whatever initialization is needed so we can say Derived is-a Base
            super(Derived, self).__init__(x)
            # now, add whatever makes Derived special - do your own initialization
            self.y = y
    

    In Python 3, you don't have to (and therefore propably shouldn't, for simplicity) explicitly inherit from object or pass the class and self to super.

提交回复
热议问题