Should __init__() call the parent class's __init__()?












113















I'm used that in Objective-C I've got this construct:



- (void)init {
if (self = [super init]) {
// init class
}
return self;
}


Should Python also call the parent class's implementation for __init__?



class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class


Is this also true/false for __new__() and __del__()?



Edit: There's a very similar question: Inheritance and Overriding __init__ in Python










share|improve this question

























  • you've changed your code significantly. I can understand that original object was a typo. But now you don't even have super title of your question refers to.

    – SilentGhost
    Sep 6 '09 at 14:18











  • I just thought that super is used as a name for the parent class. I didn't think anyone would think of the function. I'm sorry for any misunderstandings.

    – Georg Schölly
    Sep 6 '09 at 14:27











  • A why not automatic super call question: stackoverflow.com/questions/3782827/…

    – Ciro Santilli 新疆改造中心 六四事件 法轮功
    Jul 6 '15 at 8:59
















113















I'm used that in Objective-C I've got this construct:



- (void)init {
if (self = [super init]) {
// init class
}
return self;
}


Should Python also call the parent class's implementation for __init__?



class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class


Is this also true/false for __new__() and __del__()?



Edit: There's a very similar question: Inheritance and Overriding __init__ in Python










share|improve this question

























  • you've changed your code significantly. I can understand that original object was a typo. But now you don't even have super title of your question refers to.

    – SilentGhost
    Sep 6 '09 at 14:18











  • I just thought that super is used as a name for the parent class. I didn't think anyone would think of the function. I'm sorry for any misunderstandings.

    – Georg Schölly
    Sep 6 '09 at 14:27











  • A why not automatic super call question: stackoverflow.com/questions/3782827/…

    – Ciro Santilli 新疆改造中心 六四事件 法轮功
    Jul 6 '15 at 8:59














113












113








113


20






I'm used that in Objective-C I've got this construct:



- (void)init {
if (self = [super init]) {
// init class
}
return self;
}


Should Python also call the parent class's implementation for __init__?



class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class


Is this also true/false for __new__() and __del__()?



Edit: There's a very similar question: Inheritance and Overriding __init__ in Python










share|improve this question
















I'm used that in Objective-C I've got this construct:



- (void)init {
if (self = [super init]) {
// init class
}
return self;
}


Should Python also call the parent class's implementation for __init__?



class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class


Is this also true/false for __new__() and __del__()?



Edit: There's a very similar question: Inheritance and Overriding __init__ in Python







python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 23 '17 at 12:02









Community

11




11










asked Sep 6 '09 at 14:04









Georg SchöllyGeorg Schölly

99.3k42184245




99.3k42184245













  • you've changed your code significantly. I can understand that original object was a typo. But now you don't even have super title of your question refers to.

    – SilentGhost
    Sep 6 '09 at 14:18











  • I just thought that super is used as a name for the parent class. I didn't think anyone would think of the function. I'm sorry for any misunderstandings.

    – Georg Schölly
    Sep 6 '09 at 14:27











  • A why not automatic super call question: stackoverflow.com/questions/3782827/…

    – Ciro Santilli 新疆改造中心 六四事件 法轮功
    Jul 6 '15 at 8:59



















  • you've changed your code significantly. I can understand that original object was a typo. But now you don't even have super title of your question refers to.

    – SilentGhost
    Sep 6 '09 at 14:18











  • I just thought that super is used as a name for the parent class. I didn't think anyone would think of the function. I'm sorry for any misunderstandings.

    – Georg Schölly
    Sep 6 '09 at 14:27











  • A why not automatic super call question: stackoverflow.com/questions/3782827/…

    – Ciro Santilli 新疆改造中心 六四事件 法轮功
    Jul 6 '15 at 8:59

















you've changed your code significantly. I can understand that original object was a typo. But now you don't even have super title of your question refers to.

– SilentGhost
Sep 6 '09 at 14:18





you've changed your code significantly. I can understand that original object was a typo. But now you don't even have super title of your question refers to.

– SilentGhost
Sep 6 '09 at 14:18













I just thought that super is used as a name for the parent class. I didn't think anyone would think of the function. I'm sorry for any misunderstandings.

– Georg Schölly
Sep 6 '09 at 14:27





I just thought that super is used as a name for the parent class. I didn't think anyone would think of the function. I'm sorry for any misunderstandings.

– Georg Schölly
Sep 6 '09 at 14:27













A why not automatic super call question: stackoverflow.com/questions/3782827/…

– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 6 '15 at 8:59





A why not automatic super call question: stackoverflow.com/questions/3782827/…

– Ciro Santilli 新疆改造中心 六四事件 法轮功
Jul 6 '15 at 8:59












6 Answers
6






active

oldest

votes


















59














In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:



object.__init__(self)


In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.



On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.






share|improve this answer


























  • So there's no convention to just call super's implementation?

    – Georg Schölly
    Sep 6 '09 at 14:22






  • 5





    In old-style classes, you could only call the super init if the super class actually had an init defined (which it often doesn't). Therefore, people typically think about calling super method, rather than doing it out of principle.

    – Martin v. Löwis
    Sep 6 '09 at 14:47






  • 1





    If the syntax in python was as simple as [super init], it would be more common. Just a speculative thought; the super construct in Python 2.x is a bit awkward to me.

    – u0b34a0f6ae
    Sep 6 '09 at 20:34











  • Here seems to be an interesting (and possibly contradicting) example: bytes.com/topic/python/answers/…init

    – mlvljr
    Jun 7 '11 at 12:16











  • "optional" in that you don't have to call it, but if you don't call it, it's not going to get called automatically.

    – McKay
    Dec 19 '17 at 23:35



















126














If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:



>>> class C(object):
def __init__(self):
self.b = 1


>>> class D(C):
def __init__(self):
super().__init__() # in Python 2 use super(D, self).__init__()
self.a = 1


>>> class E(C):
def __init__(self):
self.a = 1


>>> d = D()
>>> d.a
1
>>> d.b # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
e.b # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'


__del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).



I rarely use __new__. I do all the initialization in __init__.






share|improve this answer





















  • 3





    The definition of class D(C) must be corrected like that super(D,self).__init__()

    – eyquem
    Aug 14 '11 at 19:15






  • 11





    super().__init__() only works in Python 3. In Python 2 you need super(D, self).__init__()

    – Jacinda
    Jun 4 '13 at 23:48



















81














In Anon's answer:
"If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"



It's incredible: he is wording exactly the contrary of the principle of inheritance.






It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__



So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??



It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.

In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.

NOT the contrary.






Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ .
That's exactly what is said in the official doc:




An overriding method in a derived class may in fact want to extend
rather than simply replace the base class method
of the same name.
There is a simple way to call the base class method directly: just
call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance




That's all the story:




  • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class


  • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class


  • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__






What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.






share|improve this answer





















  • 1





    I was sure that this post was going to be upvoted. I'm afraid that I won't have a lot of explanation about the reasons why. It's easier to downvote than to analyze a text that appears incomprehensible. I had a long time trying to understand the Anon's post before I finally realized that it was speciously written and not very much authoritative. Maybe it can be interpreted as approximately right for someone who knows about the inheritance; but I find it confusioning when read by someone having unsteady notions about inheritance, a subject not as clear as rock water in general

    – eyquem
    Aug 14 '11 at 21:50






  • 2





    "I was sure that this post was going to be upvoted..." Main issue is that you're a little late to the party, and most people may not read beyond the first few answers. Great explanation by the way +1

    – Gerrat
    Apr 6 '14 at 18:55











  • Great answer this is.

    – Trilarion
    May 20 '14 at 14:03






  • 2





    You missed the significant words "in addition" in the sentence you quoted from Aaron. Aaron's statement is completely correct, and matches what you end up saying.

    – GreenAsJade
    Jun 12 '14 at 6:06








  • 1





    This is the first explanation that made python's design choice make sense.

    – Joseph Garvin
    Jan 2 '15 at 22:59



















18














Edit: (after the code change)

There is no way for us to tell you whether you need or not to call your parent's __init__ (or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your __init__ is done in parent class, you can just skip child-class __init__ altogether.



consider the following example:



>>> class A:
def __init__(self, val):
self.a = val


>>> class B(A):
pass

>>> class C(A):
def __init__(self, val):
A.__init__(self, val)
self.a += val


>>> A(4).a
4
>>> B(5).a
5
>>> C(6).a
12





share|improve this answer


























  • I removed the super call from my example, is I wanted to know if one should call the parent class's implementation of init or not.

    – Georg Schölly
    Sep 6 '09 at 14:14











  • you might want to edit the title then. but my answer still stands.

    – SilentGhost
    Sep 6 '09 at 14:19



















4














There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.



Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render() method of a widget.



Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected is a valid concept in OOP in general (though not, of course, in Python).






share|improve this answer


























  • What about new and del?

    – Georg Schölly
    Sep 6 '09 at 14:16











  • You said that sometimes one would want to call own code before the superclass call. To do this, one needs knowledge of the parent class's implementation, which would violate the OPP.

    – Georg Schölly
    Sep 6 '09 at 16:34



















3














IMO, you should call it. If your superclass is object, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__ itself, for example when it has no (additional) internal state to initialize.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1385759%2fshould-init-call-the-parent-classs-init%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    6 Answers
    6






    active

    oldest

    votes








    6 Answers
    6






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    59














    In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:



    object.__init__(self)


    In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.



    On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.






    share|improve this answer


























    • So there's no convention to just call super's implementation?

      – Georg Schölly
      Sep 6 '09 at 14:22






    • 5





      In old-style classes, you could only call the super init if the super class actually had an init defined (which it often doesn't). Therefore, people typically think about calling super method, rather than doing it out of principle.

      – Martin v. Löwis
      Sep 6 '09 at 14:47






    • 1





      If the syntax in python was as simple as [super init], it would be more common. Just a speculative thought; the super construct in Python 2.x is a bit awkward to me.

      – u0b34a0f6ae
      Sep 6 '09 at 20:34











    • Here seems to be an interesting (and possibly contradicting) example: bytes.com/topic/python/answers/…init

      – mlvljr
      Jun 7 '11 at 12:16











    • "optional" in that you don't have to call it, but if you don't call it, it's not going to get called automatically.

      – McKay
      Dec 19 '17 at 23:35
















    59














    In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:



    object.__init__(self)


    In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.



    On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.






    share|improve this answer


























    • So there's no convention to just call super's implementation?

      – Georg Schölly
      Sep 6 '09 at 14:22






    • 5





      In old-style classes, you could only call the super init if the super class actually had an init defined (which it often doesn't). Therefore, people typically think about calling super method, rather than doing it out of principle.

      – Martin v. Löwis
      Sep 6 '09 at 14:47






    • 1





      If the syntax in python was as simple as [super init], it would be more common. Just a speculative thought; the super construct in Python 2.x is a bit awkward to me.

      – u0b34a0f6ae
      Sep 6 '09 at 20:34











    • Here seems to be an interesting (and possibly contradicting) example: bytes.com/topic/python/answers/…init

      – mlvljr
      Jun 7 '11 at 12:16











    • "optional" in that you don't have to call it, but if you don't call it, it's not going to get called automatically.

      – McKay
      Dec 19 '17 at 23:35














    59












    59








    59







    In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:



    object.__init__(self)


    In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.



    On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.






    share|improve this answer















    In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:



    object.__init__(self)


    In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.



    On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 3 at 0:11









    Nick Rempel

    2,26421629




    2,26421629










    answered Sep 6 '09 at 14:18









    Martin v. LöwisMartin v. Löwis

    98.4k14169215




    98.4k14169215













    • So there's no convention to just call super's implementation?

      – Georg Schölly
      Sep 6 '09 at 14:22






    • 5





      In old-style classes, you could only call the super init if the super class actually had an init defined (which it often doesn't). Therefore, people typically think about calling super method, rather than doing it out of principle.

      – Martin v. Löwis
      Sep 6 '09 at 14:47






    • 1





      If the syntax in python was as simple as [super init], it would be more common. Just a speculative thought; the super construct in Python 2.x is a bit awkward to me.

      – u0b34a0f6ae
      Sep 6 '09 at 20:34











    • Here seems to be an interesting (and possibly contradicting) example: bytes.com/topic/python/answers/…init

      – mlvljr
      Jun 7 '11 at 12:16











    • "optional" in that you don't have to call it, but if you don't call it, it's not going to get called automatically.

      – McKay
      Dec 19 '17 at 23:35



















    • So there's no convention to just call super's implementation?

      – Georg Schölly
      Sep 6 '09 at 14:22






    • 5





      In old-style classes, you could only call the super init if the super class actually had an init defined (which it often doesn't). Therefore, people typically think about calling super method, rather than doing it out of principle.

      – Martin v. Löwis
      Sep 6 '09 at 14:47






    • 1





      If the syntax in python was as simple as [super init], it would be more common. Just a speculative thought; the super construct in Python 2.x is a bit awkward to me.

      – u0b34a0f6ae
      Sep 6 '09 at 20:34











    • Here seems to be an interesting (and possibly contradicting) example: bytes.com/topic/python/answers/…init

      – mlvljr
      Jun 7 '11 at 12:16











    • "optional" in that you don't have to call it, but if you don't call it, it's not going to get called automatically.

      – McKay
      Dec 19 '17 at 23:35

















    So there's no convention to just call super's implementation?

    – Georg Schölly
    Sep 6 '09 at 14:22





    So there's no convention to just call super's implementation?

    – Georg Schölly
    Sep 6 '09 at 14:22




    5




    5





    In old-style classes, you could only call the super init if the super class actually had an init defined (which it often doesn't). Therefore, people typically think about calling super method, rather than doing it out of principle.

    – Martin v. Löwis
    Sep 6 '09 at 14:47





    In old-style classes, you could only call the super init if the super class actually had an init defined (which it often doesn't). Therefore, people typically think about calling super method, rather than doing it out of principle.

    – Martin v. Löwis
    Sep 6 '09 at 14:47




    1




    1





    If the syntax in python was as simple as [super init], it would be more common. Just a speculative thought; the super construct in Python 2.x is a bit awkward to me.

    – u0b34a0f6ae
    Sep 6 '09 at 20:34





    If the syntax in python was as simple as [super init], it would be more common. Just a speculative thought; the super construct in Python 2.x is a bit awkward to me.

    – u0b34a0f6ae
    Sep 6 '09 at 20:34













    Here seems to be an interesting (and possibly contradicting) example: bytes.com/topic/python/answers/…init

    – mlvljr
    Jun 7 '11 at 12:16





    Here seems to be an interesting (and possibly contradicting) example: bytes.com/topic/python/answers/…init

    – mlvljr
    Jun 7 '11 at 12:16













    "optional" in that you don't have to call it, but if you don't call it, it's not going to get called automatically.

    – McKay
    Dec 19 '17 at 23:35





    "optional" in that you don't have to call it, but if you don't call it, it's not going to get called automatically.

    – McKay
    Dec 19 '17 at 23:35













    126














    If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:



    >>> class C(object):
    def __init__(self):
    self.b = 1


    >>> class D(C):
    def __init__(self):
    super().__init__() # in Python 2 use super(D, self).__init__()
    self.a = 1


    >>> class E(C):
    def __init__(self):
    self.a = 1


    >>> d = D()
    >>> d.a
    1
    >>> d.b # This works because of the call to super's init
    1
    >>> e = E()
    >>> e.a
    1
    >>> e.b # This is going to fail since nothing in E initializes b...
    Traceback (most recent call last):
    File "<pyshell#70>", line 1, in <module>
    e.b # This is going to fail since nothing in E initializes b...
    AttributeError: 'E' object has no attribute 'b'


    __del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).



    I rarely use __new__. I do all the initialization in __init__.






    share|improve this answer





















    • 3





      The definition of class D(C) must be corrected like that super(D,self).__init__()

      – eyquem
      Aug 14 '11 at 19:15






    • 11





      super().__init__() only works in Python 3. In Python 2 you need super(D, self).__init__()

      – Jacinda
      Jun 4 '13 at 23:48
















    126














    If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:



    >>> class C(object):
    def __init__(self):
    self.b = 1


    >>> class D(C):
    def __init__(self):
    super().__init__() # in Python 2 use super(D, self).__init__()
    self.a = 1


    >>> class E(C):
    def __init__(self):
    self.a = 1


    >>> d = D()
    >>> d.a
    1
    >>> d.b # This works because of the call to super's init
    1
    >>> e = E()
    >>> e.a
    1
    >>> e.b # This is going to fail since nothing in E initializes b...
    Traceback (most recent call last):
    File "<pyshell#70>", line 1, in <module>
    e.b # This is going to fail since nothing in E initializes b...
    AttributeError: 'E' object has no attribute 'b'


    __del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).



    I rarely use __new__. I do all the initialization in __init__.






    share|improve this answer





















    • 3





      The definition of class D(C) must be corrected like that super(D,self).__init__()

      – eyquem
      Aug 14 '11 at 19:15






    • 11





      super().__init__() only works in Python 3. In Python 2 you need super(D, self).__init__()

      – Jacinda
      Jun 4 '13 at 23:48














    126












    126








    126







    If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:



    >>> class C(object):
    def __init__(self):
    self.b = 1


    >>> class D(C):
    def __init__(self):
    super().__init__() # in Python 2 use super(D, self).__init__()
    self.a = 1


    >>> class E(C):
    def __init__(self):
    self.a = 1


    >>> d = D()
    >>> d.a
    1
    >>> d.b # This works because of the call to super's init
    1
    >>> e = E()
    >>> e.a
    1
    >>> e.b # This is going to fail since nothing in E initializes b...
    Traceback (most recent call last):
    File "<pyshell#70>", line 1, in <module>
    e.b # This is going to fail since nothing in E initializes b...
    AttributeError: 'E' object has no attribute 'b'


    __del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).



    I rarely use __new__. I do all the initialization in __init__.






    share|improve this answer















    If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:



    >>> class C(object):
    def __init__(self):
    self.b = 1


    >>> class D(C):
    def __init__(self):
    super().__init__() # in Python 2 use super(D, self).__init__()
    self.a = 1


    >>> class E(C):
    def __init__(self):
    self.a = 1


    >>> d = D()
    >>> d.a
    1
    >>> d.b # This works because of the call to super's init
    1
    >>> e = E()
    >>> e.a
    1
    >>> e.b # This is going to fail since nothing in E initializes b...
    Traceback (most recent call last):
    File "<pyshell#70>", line 1, in <module>
    e.b # This is going to fail since nothing in E initializes b...
    AttributeError: 'E' object has no attribute 'b'


    __del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).



    I rarely use __new__. I do all the initialization in __init__.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Sep 24 '14 at 1:04









    osa

    4,5913443




    4,5913443










    answered Sep 6 '09 at 14:51









    AnonAnon

    8,36031818




    8,36031818








    • 3





      The definition of class D(C) must be corrected like that super(D,self).__init__()

      – eyquem
      Aug 14 '11 at 19:15






    • 11





      super().__init__() only works in Python 3. In Python 2 you need super(D, self).__init__()

      – Jacinda
      Jun 4 '13 at 23:48














    • 3





      The definition of class D(C) must be corrected like that super(D,self).__init__()

      – eyquem
      Aug 14 '11 at 19:15






    • 11





      super().__init__() only works in Python 3. In Python 2 you need super(D, self).__init__()

      – Jacinda
      Jun 4 '13 at 23:48








    3




    3





    The definition of class D(C) must be corrected like that super(D,self).__init__()

    – eyquem
    Aug 14 '11 at 19:15





    The definition of class D(C) must be corrected like that super(D,self).__init__()

    – eyquem
    Aug 14 '11 at 19:15




    11




    11





    super().__init__() only works in Python 3. In Python 2 you need super(D, self).__init__()

    – Jacinda
    Jun 4 '13 at 23:48





    super().__init__() only works in Python 3. In Python 2 you need super(D, self).__init__()

    – Jacinda
    Jun 4 '13 at 23:48











    81














    In Anon's answer:
    "If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"



    It's incredible: he is wording exactly the contrary of the principle of inheritance.






    It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__



    So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??



    It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.

    In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.

    NOT the contrary.






    Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ .
    That's exactly what is said in the official doc:




    An overriding method in a derived class may in fact want to extend
    rather than simply replace the base class method
    of the same name.
    There is a simple way to call the base class method directly: just
    call BaseClassName.methodname(self, arguments).
    http://docs.python.org/tutorial/classes.html#inheritance




    That's all the story:




    • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class


    • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class


    • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__






    What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.






    share|improve this answer





















    • 1





      I was sure that this post was going to be upvoted. I'm afraid that I won't have a lot of explanation about the reasons why. It's easier to downvote than to analyze a text that appears incomprehensible. I had a long time trying to understand the Anon's post before I finally realized that it was speciously written and not very much authoritative. Maybe it can be interpreted as approximately right for someone who knows about the inheritance; but I find it confusioning when read by someone having unsteady notions about inheritance, a subject not as clear as rock water in general

      – eyquem
      Aug 14 '11 at 21:50






    • 2





      "I was sure that this post was going to be upvoted..." Main issue is that you're a little late to the party, and most people may not read beyond the first few answers. Great explanation by the way +1

      – Gerrat
      Apr 6 '14 at 18:55











    • Great answer this is.

      – Trilarion
      May 20 '14 at 14:03






    • 2





      You missed the significant words "in addition" in the sentence you quoted from Aaron. Aaron's statement is completely correct, and matches what you end up saying.

      – GreenAsJade
      Jun 12 '14 at 6:06








    • 1





      This is the first explanation that made python's design choice make sense.

      – Joseph Garvin
      Jan 2 '15 at 22:59
















    81














    In Anon's answer:
    "If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"



    It's incredible: he is wording exactly the contrary of the principle of inheritance.






    It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__



    So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??



    It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.

    In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.

    NOT the contrary.






    Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ .
    That's exactly what is said in the official doc:




    An overriding method in a derived class may in fact want to extend
    rather than simply replace the base class method
    of the same name.
    There is a simple way to call the base class method directly: just
    call BaseClassName.methodname(self, arguments).
    http://docs.python.org/tutorial/classes.html#inheritance




    That's all the story:




    • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class


    • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class


    • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__






    What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.






    share|improve this answer





















    • 1





      I was sure that this post was going to be upvoted. I'm afraid that I won't have a lot of explanation about the reasons why. It's easier to downvote than to analyze a text that appears incomprehensible. I had a long time trying to understand the Anon's post before I finally realized that it was speciously written and not very much authoritative. Maybe it can be interpreted as approximately right for someone who knows about the inheritance; but I find it confusioning when read by someone having unsteady notions about inheritance, a subject not as clear as rock water in general

      – eyquem
      Aug 14 '11 at 21:50






    • 2





      "I was sure that this post was going to be upvoted..." Main issue is that you're a little late to the party, and most people may not read beyond the first few answers. Great explanation by the way +1

      – Gerrat
      Apr 6 '14 at 18:55











    • Great answer this is.

      – Trilarion
      May 20 '14 at 14:03






    • 2





      You missed the significant words "in addition" in the sentence you quoted from Aaron. Aaron's statement is completely correct, and matches what you end up saying.

      – GreenAsJade
      Jun 12 '14 at 6:06








    • 1





      This is the first explanation that made python's design choice make sense.

      – Joseph Garvin
      Jan 2 '15 at 22:59














    81












    81








    81







    In Anon's answer:
    "If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"



    It's incredible: he is wording exactly the contrary of the principle of inheritance.






    It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__



    So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??



    It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.

    In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.

    NOT the contrary.






    Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ .
    That's exactly what is said in the official doc:




    An overriding method in a derived class may in fact want to extend
    rather than simply replace the base class method
    of the same name.
    There is a simple way to call the base class method directly: just
    call BaseClassName.methodname(self, arguments).
    http://docs.python.org/tutorial/classes.html#inheritance




    That's all the story:




    • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class


    • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class


    • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__






    What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.






    share|improve this answer















    In Anon's answer:
    "If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"



    It's incredible: he is wording exactly the contrary of the principle of inheritance.






    It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__



    So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??



    It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.

    In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.

    NOT the contrary.






    Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ .
    That's exactly what is said in the official doc:




    An overriding method in a derived class may in fact want to extend
    rather than simply replace the base class method
    of the same name.
    There is a simple way to call the base class method directly: just
    call BaseClassName.methodname(self, arguments).
    http://docs.python.org/tutorial/classes.html#inheritance




    That's all the story:




    • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class


    • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class


    • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__






    What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 27 '18 at 1:33









    Bruce

    33928




    33928










    answered Aug 14 '11 at 20:31









    eyquemeyquem

    20.2k42939




    20.2k42939








    • 1





      I was sure that this post was going to be upvoted. I'm afraid that I won't have a lot of explanation about the reasons why. It's easier to downvote than to analyze a text that appears incomprehensible. I had a long time trying to understand the Anon's post before I finally realized that it was speciously written and not very much authoritative. Maybe it can be interpreted as approximately right for someone who knows about the inheritance; but I find it confusioning when read by someone having unsteady notions about inheritance, a subject not as clear as rock water in general

      – eyquem
      Aug 14 '11 at 21:50






    • 2





      "I was sure that this post was going to be upvoted..." Main issue is that you're a little late to the party, and most people may not read beyond the first few answers. Great explanation by the way +1

      – Gerrat
      Apr 6 '14 at 18:55











    • Great answer this is.

      – Trilarion
      May 20 '14 at 14:03






    • 2





      You missed the significant words "in addition" in the sentence you quoted from Aaron. Aaron's statement is completely correct, and matches what you end up saying.

      – GreenAsJade
      Jun 12 '14 at 6:06








    • 1





      This is the first explanation that made python's design choice make sense.

      – Joseph Garvin
      Jan 2 '15 at 22:59














    • 1





      I was sure that this post was going to be upvoted. I'm afraid that I won't have a lot of explanation about the reasons why. It's easier to downvote than to analyze a text that appears incomprehensible. I had a long time trying to understand the Anon's post before I finally realized that it was speciously written and not very much authoritative. Maybe it can be interpreted as approximately right for someone who knows about the inheritance; but I find it confusioning when read by someone having unsteady notions about inheritance, a subject not as clear as rock water in general

      – eyquem
      Aug 14 '11 at 21:50






    • 2





      "I was sure that this post was going to be upvoted..." Main issue is that you're a little late to the party, and most people may not read beyond the first few answers. Great explanation by the way +1

      – Gerrat
      Apr 6 '14 at 18:55











    • Great answer this is.

      – Trilarion
      May 20 '14 at 14:03






    • 2





      You missed the significant words "in addition" in the sentence you quoted from Aaron. Aaron's statement is completely correct, and matches what you end up saying.

      – GreenAsJade
      Jun 12 '14 at 6:06








    • 1





      This is the first explanation that made python's design choice make sense.

      – Joseph Garvin
      Jan 2 '15 at 22:59








    1




    1





    I was sure that this post was going to be upvoted. I'm afraid that I won't have a lot of explanation about the reasons why. It's easier to downvote than to analyze a text that appears incomprehensible. I had a long time trying to understand the Anon's post before I finally realized that it was speciously written and not very much authoritative. Maybe it can be interpreted as approximately right for someone who knows about the inheritance; but I find it confusioning when read by someone having unsteady notions about inheritance, a subject not as clear as rock water in general

    – eyquem
    Aug 14 '11 at 21:50





    I was sure that this post was going to be upvoted. I'm afraid that I won't have a lot of explanation about the reasons why. It's easier to downvote than to analyze a text that appears incomprehensible. I had a long time trying to understand the Anon's post before I finally realized that it was speciously written and not very much authoritative. Maybe it can be interpreted as approximately right for someone who knows about the inheritance; but I find it confusioning when read by someone having unsteady notions about inheritance, a subject not as clear as rock water in general

    – eyquem
    Aug 14 '11 at 21:50




    2




    2





    "I was sure that this post was going to be upvoted..." Main issue is that you're a little late to the party, and most people may not read beyond the first few answers. Great explanation by the way +1

    – Gerrat
    Apr 6 '14 at 18:55





    "I was sure that this post was going to be upvoted..." Main issue is that you're a little late to the party, and most people may not read beyond the first few answers. Great explanation by the way +1

    – Gerrat
    Apr 6 '14 at 18:55













    Great answer this is.

    – Trilarion
    May 20 '14 at 14:03





    Great answer this is.

    – Trilarion
    May 20 '14 at 14:03




    2




    2





    You missed the significant words "in addition" in the sentence you quoted from Aaron. Aaron's statement is completely correct, and matches what you end up saying.

    – GreenAsJade
    Jun 12 '14 at 6:06







    You missed the significant words "in addition" in the sentence you quoted from Aaron. Aaron's statement is completely correct, and matches what you end up saying.

    – GreenAsJade
    Jun 12 '14 at 6:06






    1




    1





    This is the first explanation that made python's design choice make sense.

    – Joseph Garvin
    Jan 2 '15 at 22:59





    This is the first explanation that made python's design choice make sense.

    – Joseph Garvin
    Jan 2 '15 at 22:59











    18














    Edit: (after the code change)

    There is no way for us to tell you whether you need or not to call your parent's __init__ (or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your __init__ is done in parent class, you can just skip child-class __init__ altogether.



    consider the following example:



    >>> class A:
    def __init__(self, val):
    self.a = val


    >>> class B(A):
    pass

    >>> class C(A):
    def __init__(self, val):
    A.__init__(self, val)
    self.a += val


    >>> A(4).a
    4
    >>> B(5).a
    5
    >>> C(6).a
    12





    share|improve this answer


























    • I removed the super call from my example, is I wanted to know if one should call the parent class's implementation of init or not.

      – Georg Schölly
      Sep 6 '09 at 14:14











    • you might want to edit the title then. but my answer still stands.

      – SilentGhost
      Sep 6 '09 at 14:19
















    18














    Edit: (after the code change)

    There is no way for us to tell you whether you need or not to call your parent's __init__ (or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your __init__ is done in parent class, you can just skip child-class __init__ altogether.



    consider the following example:



    >>> class A:
    def __init__(self, val):
    self.a = val


    >>> class B(A):
    pass

    >>> class C(A):
    def __init__(self, val):
    A.__init__(self, val)
    self.a += val


    >>> A(4).a
    4
    >>> B(5).a
    5
    >>> C(6).a
    12





    share|improve this answer


























    • I removed the super call from my example, is I wanted to know if one should call the parent class's implementation of init or not.

      – Georg Schölly
      Sep 6 '09 at 14:14











    • you might want to edit the title then. but my answer still stands.

      – SilentGhost
      Sep 6 '09 at 14:19














    18












    18








    18







    Edit: (after the code change)

    There is no way for us to tell you whether you need or not to call your parent's __init__ (or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your __init__ is done in parent class, you can just skip child-class __init__ altogether.



    consider the following example:



    >>> class A:
    def __init__(self, val):
    self.a = val


    >>> class B(A):
    pass

    >>> class C(A):
    def __init__(self, val):
    A.__init__(self, val)
    self.a += val


    >>> A(4).a
    4
    >>> B(5).a
    5
    >>> C(6).a
    12





    share|improve this answer















    Edit: (after the code change)

    There is no way for us to tell you whether you need or not to call your parent's __init__ (or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your __init__ is done in parent class, you can just skip child-class __init__ altogether.



    consider the following example:



    >>> class A:
    def __init__(self, val):
    self.a = val


    >>> class B(A):
    pass

    >>> class C(A):
    def __init__(self, val):
    A.__init__(self, val)
    self.a += val


    >>> A(4).a
    4
    >>> B(5).a
    5
    >>> C(6).a
    12






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Sep 6 '09 at 14:29

























    answered Sep 6 '09 at 14:11









    SilentGhostSilentGhost

    199k47270266




    199k47270266













    • I removed the super call from my example, is I wanted to know if one should call the parent class's implementation of init or not.

      – Georg Schölly
      Sep 6 '09 at 14:14











    • you might want to edit the title then. but my answer still stands.

      – SilentGhost
      Sep 6 '09 at 14:19



















    • I removed the super call from my example, is I wanted to know if one should call the parent class's implementation of init or not.

      – Georg Schölly
      Sep 6 '09 at 14:14











    • you might want to edit the title then. but my answer still stands.

      – SilentGhost
      Sep 6 '09 at 14:19

















    I removed the super call from my example, is I wanted to know if one should call the parent class's implementation of init or not.

    – Georg Schölly
    Sep 6 '09 at 14:14





    I removed the super call from my example, is I wanted to know if one should call the parent class's implementation of init or not.

    – Georg Schölly
    Sep 6 '09 at 14:14













    you might want to edit the title then. but my answer still stands.

    – SilentGhost
    Sep 6 '09 at 14:19





    you might want to edit the title then. but my answer still stands.

    – SilentGhost
    Sep 6 '09 at 14:19











    4














    There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.



    Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render() method of a widget.



    Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected is a valid concept in OOP in general (though not, of course, in Python).






    share|improve this answer


























    • What about new and del?

      – Georg Schölly
      Sep 6 '09 at 14:16











    • You said that sometimes one would want to call own code before the superclass call. To do this, one needs knowledge of the parent class's implementation, which would violate the OPP.

      – Georg Schölly
      Sep 6 '09 at 16:34
















    4














    There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.



    Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render() method of a widget.



    Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected is a valid concept in OOP in general (though not, of course, in Python).






    share|improve this answer


























    • What about new and del?

      – Georg Schölly
      Sep 6 '09 at 14:16











    • You said that sometimes one would want to call own code before the superclass call. To do this, one needs knowledge of the parent class's implementation, which would violate the OPP.

      – Georg Schölly
      Sep 6 '09 at 16:34














    4












    4








    4







    There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.



    Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render() method of a widget.



    Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected is a valid concept in OOP in general (though not, of course, in Python).






    share|improve this answer















    There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.



    Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render() method of a widget.



    Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected is a valid concept in OOP in general (though not, of course, in Python).







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Sep 6 '09 at 19:23

























    answered Sep 6 '09 at 14:13









    Vinay SajipVinay Sajip

    71k8130146




    71k8130146













    • What about new and del?

      – Georg Schölly
      Sep 6 '09 at 14:16











    • You said that sometimes one would want to call own code before the superclass call. To do this, one needs knowledge of the parent class's implementation, which would violate the OPP.

      – Georg Schölly
      Sep 6 '09 at 16:34



















    • What about new and del?

      – Georg Schölly
      Sep 6 '09 at 14:16











    • You said that sometimes one would want to call own code before the superclass call. To do this, one needs knowledge of the parent class's implementation, which would violate the OPP.

      – Georg Schölly
      Sep 6 '09 at 16:34

















    What about new and del?

    – Georg Schölly
    Sep 6 '09 at 14:16





    What about new and del?

    – Georg Schölly
    Sep 6 '09 at 14:16













    You said that sometimes one would want to call own code before the superclass call. To do this, one needs knowledge of the parent class's implementation, which would violate the OPP.

    – Georg Schölly
    Sep 6 '09 at 16:34





    You said that sometimes one would want to call own code before the superclass call. To do this, one needs knowledge of the parent class's implementation, which would violate the OPP.

    – Georg Schölly
    Sep 6 '09 at 16:34











    3














    IMO, you should call it. If your superclass is object, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__ itself, for example when it has no (additional) internal state to initialize.






    share|improve this answer




























      3














      IMO, you should call it. If your superclass is object, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__ itself, for example when it has no (additional) internal state to initialize.






      share|improve this answer


























        3












        3








        3







        IMO, you should call it. If your superclass is object, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__ itself, for example when it has no (additional) internal state to initialize.






        share|improve this answer













        IMO, you should call it. If your superclass is object, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__ itself, for example when it has no (additional) internal state to initialize.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Sep 6 '09 at 14:47









        u0b34a0f6aeu0b34a0f6ae

        33.1k117796




        33.1k117796






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1385759%2fshould-init-call-the-parent-classs-init%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            The term 'EXEC' is not recognized as the name of a cmdlet Powershell

            NPM command prompt closes immediately [closed]

            Error binding properties and functions in emscripten