Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when your class does not explicitly define an __init__ method?

Tags:

python

class

How does the quality of my code gets affected if I don't use __init__ method in python? A simple example would be appreciated.

like image 725
Monojit Sarkar Avatar asked Mar 22 '26 01:03

Monojit Sarkar


2 Answers

Short answer; nothing happens.

Long answer; if you have a class B, which inherits from a class A, and if B has no __init__ method defined, then the parent's (in this case, A) __init__ is invoked.

In [137]: class A:
     ...:     def __init__(self):
     ...:         print("In A")
     ...:         

In [138]: class B(A): pass

In [139]: B()
In A
Out[139]: <__main__.B at 0x1230a5ac8>

If A has no predecessor, then the almighty superclass object's __init__ is invoked, which does nothing.

You can view class hierarchy by querying the dunder __mro__.

In [140]: B.__mro__
Out[140]: (__main__.B, __main__.A, object)

Also see Why do we use __init__ in Python classes? for some context as to when and where its usage is appropriate.

like image 141
cs95 Avatar answered Mar 24 '26 15:03

cs95


Its not a matter of quality here, in Object-oriented-design which python supports, __init__ is way to supply data when an object is created first. In OOPS, this is called a constructor. In other words A constructor is a method which prepares a valid object.

There are design patters on large projects are build that rely on the constructor feature provided by python. Without this they will not function,

for e.g.

  • You want to keep track of every object that is created for a class, now you need a method which is executed every time a object is created, hence the constructor.

  • Other useful example for a constructor is lets say you want to create a customer object for a Bank. Now a customer for a bank will must have an account number, so basically you have to set a rule for a valid customer object for a Bank hence the constructor.

like image 29
Muku Avatar answered Mar 24 '26 15:03

Muku