Constructors in Python Classes
Use the __init__ constructor to initialize new objects with default and custom values.
BeginnerTopic: Object-Oriented Programs
Python Constructors in Python Classes Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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
Understanding Constructors in Python Classes
__init__ allows default parameter values and custom initialization when creating objects.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.