Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is __init__ apparently optional?

While experimenting, I wrote:

class Bag:   
    pass

g = Bag()
print(g)

Which gave me:

<__main__.Bag object at 0x00000000036F0748>

Which surprised me. I expected an error when I tried to initialize it, since I didn't define __init___.

Why isn't this the case?

like image 216
temporary_user_name Avatar asked Dec 15 '22 06:12

temporary_user_name


2 Answers

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

In other words:

If you don't override __init__, the __init__ method of the superclass will be called.

E.g.

class Bag:
    pass

if equivalent to:

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

Furthermore, __init__ is indeed optional. It is an initializer for an instance.

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

So in practice even:

class Bag:
    def __init__(self):
        pass

Will work just fine.

like image 99
Kimvais Avatar answered Dec 23 '22 18:12

Kimvais


__init__ is an intializer not the constructor, If an __init__ method is defined it is used just to initialize the created object with the values provided as arguments. An object anyhow gets created even if an __init__ method is not defined for the class, however not initialized, as __init__ method is not overridden to customize as per your needs.

like image 42
pythoneer.farhat Avatar answered Dec 23 '22 19:12

pythoneer.farhat