Python class without Constructor the Calculator example
Why Does the Calculator Example Work Without a Constructor?
Excellent observation.
The answer is No, we're not missing the constructor. A class does not need to have a constructor.
This is completely valid Python:
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
c = Calculator()
print(c.add(10, 5))
print(c.multiply(10, 5))
Why Does It Work Without __init__()?
Because the Calculator object has no attributes that need initialization.
The methods:
def add(self, a, b):
and
def multiply(self, a, b):
simply take inputs and return results.
They don't need to store any data inside the object.
Think About It
When you create:
c = Calculator()
there is nothing to initialize.
The object doesn't need:
- name
- age
- brand
- balance
or any other stored data.
So a constructor is unnecessary.
Python Secret
Even though you didn't write a constructor, Python provides a default one.
Internally it's similar to:
class Calculator:
def __init__(self):
pass
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
Python automatically gives you an empty constructor.
When Do We Need a Constructor?
When an object must store data.
Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
Here:
s1 = Student("John", 20)
creates an object with data:
s1
├── name = John
└── age = 20
Without __init__(), those attributes wouldn't exist.
Calculator Example With Constructor
Suppose we want every calculator to remember its owner's name.
class Calculator:
def __init__(self, owner):
self.owner = owner
def add(self, a, b):
return a + b
c = Calculator("Rakesh")
print(c.owner)
print(c.add(10, 5))
Output:
Rakesh
15
Now we need a constructor because we're storing:
self.owner
inside the object.
Rule to Remember
Constructor Required
When the object needs to store data.
class Student:
def __init__(self, name):
self.name = name
Constructor Optional
When the class only provides behavior (methods).
class Calculator:
def add(self, a, b):
return a + b
Interview Question
Q: Is __init__() mandatory in Python classes?
Answer: No.
If you don't define a constructor, Python automatically provides a default empty constructor.
class Test:
pass
obj = Test() # perfectly valid
So the Calculator example is actually demonstrating an important idea:
A class can exist purely to provide methods, and such a class may not need any constructor or attributes at all.