0
0
Pythonprogramming~5 mins

Constructor parameters in Python

Choose your learning style9 modes available
Introduction

Constructor parameters let you give information to an object when you create it. This helps set up the object with the details it needs right away.

When you want to create a new object with specific details, like a person's name or age.
When you want to make sure an object always has certain information from the start.
When you want to create many objects with different values easily.
When you want to avoid setting object details later with extra steps.
Syntax
Python
class ClassName:
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2

The __init__ method is the constructor in Python.

Parameters inside __init__ let you pass values when creating an object.

Examples
This example creates a Dog with a name given when making the object.
Python
class Dog:
    def __init__(self, name):
        self.name = name

my_dog = Dog("Buddy")
print(my_dog.name)
This example shows a constructor with two parameters to set make and year.
Python
class Car:
    def __init__(self, make, year):
        self.make = make
        self.year = year

my_car = Car("Toyota", 2020)
print(my_car.make, my_car.year)
Sample Program

This program creates a Book object with title and author given as constructor parameters. It then prints these details.

Python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

my_book = Book("1984", "George Orwell")
print(f"Title: {my_book.title}")
print(f"Author: {my_book.author}")
OutputSuccess
Important Notes

Constructor parameters help keep your code clean by setting values when the object is made.

You can have as many parameters as you need, but keep it simple to avoid confusion.

Summary

Constructor parameters let you give objects information when you create them.

This helps set up objects quickly and correctly.

Use __init__ method in Python to define constructor parameters.