Constructors in Python Classes

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

PythonBeginner
Python
# Program to demonstrate constructors

class Rectangle:
    def __init__(self, width=1, height=1):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height


default_rect = Rectangle()
custom_rect = Rectangle(4, 5)

print("Default area:", default_rect.area())
print("Custom area:", custom_rect.area())

Output

Default area: 1
Custom area: 20

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