4

Since calling className() will execute the code in __init__(args), why in the code below, is someone explicitly calling __init__?

class Example(Frame):
 def __init__(self, parent):
 Frame.__init__(self, parent) 

Is there any difference in the actual code that is executed between the two method calls, or is chossing __init__() over className() simply arbitrary?

Running Python 3.4

famousgarkin
14.2k5 gold badges60 silver badges74 bronze badges
asked Jun 26, 2014 at 18:51

1 Answer 1

9

className() does more than call __init__. It also calls __new__, which creates a new instance of the class. So calling Frame() would not do the superclass initialization on the same self object; it would create a new object and initialize that.

You call __init__ when you want to run just __init__ on a particular instance you've already created. Typically this is in a situation like the one you show, where you want to let a superclass do its initialization on top of a subclass's initialization.

answered Jun 26, 2014 at 18:53
Sign up to request clarification or add additional context in comments.

4 Comments

so calling Frame's __init__ is like calling super() in java?
@joshsvoss: Possibly. I don't really know Java. My experience with answering questions on this site is that people usually wind up with a better understanding if they try to understand what Python actually does instead of mapping it onto Java.
You can also use super(Frame, self).__init__(parent), but I confess that I don't completely understand the difference in this context.
@daniel: Yeah, that's sort of a separate issue though. Basically the super way is more flexible in case you later rearrange the class hierarchy.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.