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

- 379,657
- 97
- 704
- 746

- 657
- 1
- 5
- 15
-
quality is a word depends on you. Without init there can be quality code but you understand why constructors are important in any class (generalised to every class in every language) – Arpit Solanki Jan 16 '18 at 10:49
-
I can't see any constructive way to answer this that isn't just a broad-ranging discussion of OO principles. Maybe you could try writing some non-toy classes with and without using `__init__`, see what you think the differences are, and ask a question about your real code if you need to? – Useless Jan 16 '18 at 10:55
-
BTW - the _title_ is a perfectly answerable question. The bit about the quality of your code is the part that makes it over-broad. That's a _huge_ discussion. – Useless Jan 16 '18 at 11:02
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.

- 379,657
- 97
- 704
- 746
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 anaccount number
, so basically you have to set a rule for a valid customer object for a Bank hence the constructor.

- 538
- 4
- 18