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 browser1# Program to demonstrate constructors23class Rectangle:4 def __init__(self, width=1, height=1):5 self.width = width6 self.height = height78 def area(self):9 return self.width * self.height1011default_rect = Rectangle()12custom_rect = Rectangle(4, 5)1314print("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.