Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python - Constructors (Complete Guide for Beginners)

In Python Object-Oriented Programming (OOP), a constructor is a special method that is automatically called when an object is created. Constructors are used to initialize object attributes and perform setup tasks when a new instance of a class is created.

Python uses the __init__() method as its constructor.

In this tutorial, you will learn everything about Python constructors with practical examples.


What is a Constructor?

A constructor is a special method that:

  • Runs automatically when an object is created
  • Initializes object attributes
  • Helps set default values
  • Reduces repetitive code

The constructor method in Python is:

__init__()

Why Use Constructors?

Without constructors, you would need to manually assign values after creating objects.

Constructors help:

  • Initialize data automatically
  • Improve code readability
  • Create objects efficiently
  • Ensure every object starts with required values

Basic Constructor Example

Syntax

class ClassName:

    def __init__(self):
        pass

Creating Your First Constructor

Example

class Student:

    def __init__(self):
        print("Student object created")

s1 = Student()

Output

Student object created

The constructor runs automatically when the object is created.


Constructor with Parameters

Most constructors accept parameters to initialize object data.

Example

class Student:

    def __init__(self, name):
        self.name = name

s1 = Student("John")

print(s1.name)

Output

John

Multiple Parameters in Constructor

Example

class Student:

    def __init__(self, name, age):
        self.name = name
        self.age = age

s1 = Student("John", 20)

print(s1.name)
print(s1.age)

Output

John
20

Understanding self in Constructors

The self parameter refers to the current object.

Example

class Car:

    def __init__(self, brand):
        self.brand = brand

car1 = Car("Toyota")

print(car1.brand)

Output

Toyota

Creating Multiple Objects

Each object gets its own copy of instance attributes.

Example

class Employee:

    def __init__(self, name):
        self.name = name

e1 = Employee("Ali")
e2 = Employee("Sara")

print(e1.name)
print(e2.name)

Output

Ali
Sara

Constructor with Default Values

You can provide default parameter values.

Example

class User:

    def __init__(self, name="Guest"):
        self.name = name

u1 = User()
u2 = User("John")

print(u1.name)
print(u2.name)

Output

Guest
John

Constructor Initializing Multiple Attributes

Example

class Product:

    def __init__(self, name, price, stock):
        self.name = name
        self.price = price
        self.stock = stock

product = Product("Laptop", 800, 10)

print(product.name)
print(product.price)
print(product.stock)

Constructor and Methods Together

Example

class Student:

    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def display(self):
        print("Name:", self.name)
        print("Marks:", self.marks)

s1 = Student("John", 90)

s1.display()

Real-World Example: Bank Account

class BankAccount:

    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def show_balance(self):
        print("Balance:", self.balance)

account = BankAccount("John", 1000)

account.show_balance()

Output

Balance: 1000

Real-World Example: Car Management System

class Car:

    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

    def show_info(self):
        print(self.brand, self.model, self.year)

car1 = Car("Toyota", "Corolla", 2025)

car1.show_info()

Constructor with Calculations

Example

class Rectangle:

    def __init__(self, length, width):
        self.length = length
        self.width = width
        self.area = length * width

rect = Rectangle(10, 5)

print(rect.area)

Output

50

Difference Between Constructor and Normal Method

ConstructorNormal Method
Uses __init__()Uses any method name
Called automaticallyCalled manually
Initializes objectsPerforms actions
Runs once during creationRuns whenever called

Common Mistakes

Mistake 1: Misspelling init

❌ Wrong

class Test:

    def init(self):
        pass

✔ Correct

class Test:

    def __init__(self):
        pass

Mistake 2: Forgetting self

❌ Wrong

def __init__(name):
    pass

✔ Correct

def __init__(self, name):
    pass

Mistake 3: Wrong Number of Arguments

❌ Wrong

student = Student()

When constructor requires parameters.

✔ Correct

student = Student("John")

Best Practices

  • Always use meaningful parameter names.
  • Initialize all required attributes in the constructor.
  • Keep constructors simple.
  • Avoid putting complex business logic inside constructors.
  • Use default values when appropriate.

Constructor Summary

FeatureDescription
Method Name__init__()
PurposeInitialize objects
CalledAutomatically
Usesself
Accepts ParametersYes
Creates AttributesYes

Practical Example: Library System

class Book:

    def __init__(self, title, author):
        self.title = title
        self.author = author

    def display(self):
        print("Title:", self.title)
        print("Author:", self.author)

book1 = Book("Python Basics", "John Smith")

book1.display()

Conclusion

Constructors are one of the most important features of Python OOP. They help initialize objects automatically and ensure that every object starts with the required data.

You learned:

  • What constructors are
  • How __init__() works
  • Constructors with parameters
  • Default values
  • Real-world examples
  • Common mistakes and best practices

Understanding constructors is essential for building professional and scalable Python applications.


Practice Exercises

Exercise 1

Create a Student class with a constructor that stores:

  • Name
  • Age
  • Grade

Display all values.


Exercise 2

Create a Car class with:

  • Brand
  • Model
  • Year

Add a method to display car information.


Exercise 3

Create a Rectangle class whose constructor calculates and stores the area.




Post a Comment

0 Comments