[Tutor] __init__

Steven D'Aprano steve at pearwood.info
Mon Aug 29 20:42:59 EDT 2016


On Mon, Aug 29, 2016 at 07:03:31PM +0000, monikajg at netzero.net wrote:
> 
> 
> Hi:
> If __init__ is not defined in a class, will it be called when creating an instance?

Yes, because the default __init__ does nothing. So if you don't need an 
__init__, just don't bother to write it! Try experimenting with code 
like this at the interactive interpreter:


# Wrong, don't do this:
class MyObject():
    def __init__(self):
        # Do nothing!
        pass
    def method(self):
        print("called method")



# Better:
class MyObject():
    def method(self):
        print("called method")


obj = MyObject()




> What in a case if this class inherits from parent with __init__ and without __init__?

If you use super(), Python will work out what to do. So long as all the 
existing __init__ methods take the same arguments, use super().

If they take different arguments, you can't use super() and have to do 
it by hand.

I see you are doing a lot of multiple inheritence (MI). I don't want to 
discourage you, but MI is considered an advanced subject. (Most 
programming languages don't even support it!) You should make sure you 
understand single inheritence and super() very well before tackling MI, 
otherwise you're likely to get confused.

In any case, feel free to ask questions or ask for clarifications, and 
we'll answer as best we can.


-- 
Steve


More information about the Tutor mailing list