Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why call '__init__' instead of className()?

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

like image 687
AllTradesJack Avatar asked Jan 10 '23 08:01

AllTradesJack


1 Answers

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.

like image 174
BrenBarn Avatar answered Jan 20 '23 16:01

BrenBarn