Why is __init__ explicitly optional?

During the experiments, I wrote:

class Bag: pass g = Bag() print(g) 

Who gave me:

 <__main__.Bag object at 0x00000000036F0748> 

What surprised me. I was expecting an error when I tried to initialize it, since I did not define __init___ .

Why is this not so?

+4
source share
3 answers

You only need to override the methods you want to change.

In other words:

If you do not override __init__ , the __init__ method of the superclass is called.

eg.

 class Bag: pass 

if equivalent:

 class Bag: def __init__(self): super(Bag, self).__init__() 

In addition, __init__ indeed optional. This is the initializer for the instance .

When you create an instance of the class (by calling it), the constructor for the class is called (class method __new__ ). The constructor returns the instance for which __init__ is called.

So in practice even:

 class Bag: def __init__(self): pass 

Will work fine.

+10
source

__init__ is an intializer, not a constructor. If the __init__ method is defined, it is used only to initialize the created object with the values ​​provided as arguments. Any object is created even if the __init__ method is not defined for the class, but is not initialized, since the __init__ method is not overridden for customization according to your needs.

+1
source

You do not need to include the __init__ method if you are not going to add / change its functionality. Everything in python is an object, and python objects have a number of built-in methods, some of which you can include when creating your own object, and some of which you cannot. This is not a bad reference to learn about built-in methods.

http://www.rafekettler.com/magicmethods.html

I could add one thing. If you intend to use the super function, it is recommended that you define objects that inherit from object . This may not be required in python 3+, but it is certainly true for some of the older versions.

 class Bag(object): def __init__(self): super(Bag, self).__init__() # Adding extra functionality here. 
+1
source

All Articles