Constructors in Python — Python Technical Interview Questions & Answers
Constructors in Python
Constructors in Python
- __init__ is the initializer most people mean by constructor. It runs when you create the object: s = Student("Asha", 12). Inside, self.name = name stores fields. You do not call __init__ yourself. Student(...) does it. Forget self on the first parameter and you get TypeError.
- __new__ actually creates the instance — advanced, skip unless they ask. Viva signature: def __init__(self, name, roll). Then one object on the board: print(s.name) → Asha.
- Constructors in Python — output: 4. Box(4) calls __init__ and sets side.
Technical Interview Tip: __init__(self, ...) + one Student example.
Code Examples for Constructors in Python
Example
# Constructor
class Box:
def __init__(self, side):
self.side = side
b = Box(4)
print(b.side)
Constructors in Python — output: 4. Box(4) calls __init__ and sets side.
How to Explain Constructors in Python to an Interviewer
Explain Constructors as if you are teaching a junior — definition, then one tiny script.
__init__ runs on create. self first. Store attributes.
What does the example print, and why?
Constructors in Python — output: 4
What mistake do freshers make with Constructors?
Don’t call __init__ by hand.