python __init__ method in inherited class

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

    First of all you're mixing __init__ and __new__, they are different things. __new__ doesn't take instance (self) as argument, it takes class (cls). As for the main part of your question, what you have to do is use super to invoke superclass' __init__.

    Your code should look like this:

    class initialclass(object):
        def __init__(self):
            self.attr1 = 'one'
            self.attr2 = 'two'    
    
    class inheritedclass(initialclass):
        def __init__(self):
            self.attr3 = 'three'
            super(inheritedclass, self).__init__()
    

提交回复
热议问题