How does the quality of my code gets affected if I don't use __init__ method in python? A simple example would be appreciated.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With