Constructors in Python Classes

Use the __init__ constructor to initialize new objects with default and custom values.

BeginnerObject-Oriented ProgramsExample 3 of 25
constructors-in-python-classes.py
Run in browser
1# Program to demonstrate constructors
2
3class Rectangle:
4 def __init__(self, width=1, height=1):
5 self.width = width
6 self.height = height
7
8 def area(self):
9 return self.width * self.height
10
11default_rect = Rectangle()
12custom_rect = Rectangle(4, 5)
13
14print("Default area:", default_rect.area())
15print("Custom area:", custom_rect.area())

Output

Default area: 1
Custom area: 20

What's going on

__init__ allows default parameter values and custom initialization when creating objects.