PyLearn Object-Oriented Programming Python Constructors
Lesson 44 Object-Oriented Programming

Python Constructors

Learn how Python constructors automatically initialize objects, how the __init__() method works, and how to create clean, reusable classes with properly initialized attributes.

45–55 minutes Beginner → Intermediate Object-Oriented Programming
0%
01

Learning Objectives

In the previous lesson, you learned that classes act as blueprints and objects are instances created from those classes.

Now we will learn how to automatically give newly created objects their initial data.

By the end of this lesson, you will be able to:

  • Understand what a constructor is.
  • Understand the purpose of __init__().
  • Initialize object attributes automatically.
  • Pass values when creating objects.
  • Use constructor parameters.
  • Use default parameter values.
  • Validate data during object creation.
  • Build practical classes using constructors.
02

What Is a Constructor?

A constructor is a special method that runs automatically when an object is created.

In Python, the method commonly used for initializing objects is called __init__().

Its main purpose is to initialize the object's attributes with appropriate starting values.

Think about it this way

Without a constructor, you may have to create an object first and then manually assign its data. A constructor lets you provide that data at the moment the object is created.

03

Why Use Constructors?

Consider the approach from the previous lesson:

Without Constructor
class Student:
    pass


student = Student()

student.name = "Ali"
student.age = 22
student.course = "Python"

This works, but there is a better and more structured approach.

With Constructor
class Student:

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


student = Student("Ali", 22, "Python")

The advantage

The object is created with all of its required information in one clear statement.

04

The __init__() Method

The double underscores around init are important.

The method is written as:

Python
def __init__(self):
    # initialization code
    pass

When you create an object like this:

Object Creation
student = Student()

Python automatically calls the class's __init__() method as part of creating and initializing that object.

Important terminology

You will often hear __init__() called the Python constructor. More precisely, __init__() initializes an already created instance; Python's object creation process also involves __new__(), which you generally do not need at this stage.

05

Creating a Basic Constructor

Let's create a simple Student class.

Python
class Student:

    def __init__(self):
        self.name = "Unknown"
        self.age = 0


student = Student()

print(student.name)
print(student.age)
Output
Unknown
0

The attributes were created automatically when the object was initialized.

06

Understanding self

The first parameter of an instance constructor is normally self.

It represents the current object.

Python
class Student:

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


student = Student("Ali")

print(student.name)
Output
Ali

Here:

  • name is the constructor parameter.
  • self.name is the object's attribute.
  • "Ali" is passed into the constructor.

Important distinction

name exists as a local parameter while the constructor is running. self.name stores that value on the object so it can be used later.

07

Constructor Parameters

Constructors become especially useful when they accept parameters.

Python
class Student:

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


student = Student("Sara", 21)

print(student.name)
print(student.age)
Output
Sara
21

The values supplied during object creation are passed to __init__().

Flow
Student("Sara", 21)
        ↓
__init__(self, "Sara", 21)
        ↓
self.name = "Sara"
self.age = 21
08

Initializing Multiple Attributes

A constructor can initialize as many related attributes as your class requires.

Product Example
class Product:

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


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

print(product.name)
print(product.price)
print(product.stock)
Output
Laptop
85000
10

This pattern is extremely common in real-world applications such as ecommerce systems, inventory software, CRM systems, and business applications.

09

Creating Multiple Objects

Once a constructor is defined, we can easily create many objects with different values.

Python
class Product:

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


product1 = Product("Laptop", 85000)
product2 = Product("Phone", 50000)
product3 = Product("Headphones", 8000)

print(product1.name, product1.price)
print(product2.name, product2.price)
print(product3.name, product3.price)
Output
Laptop 85000
Phone 50000
Headphones 8000

One blueprint, many objects

The class defines the structure once, while each object stores its own values.

10

Default Constructor Values

Constructor parameters can have default values, just like normal Python function parameters.

Python
class Student:

    def __init__(self, name, course="Python"):
        self.name = name
        self.course = course


student1 = Student("Ali")
student2 = Student("Sara", "Data Analytics")

print(student1.name, student1.course)
print(student2.name, student2.course)
Output
Ali Python
Sara Data Analytics

If a value is not supplied, Python uses the default value.

11

Using Keyword Arguments

Constructor arguments can also be passed by name.

Python
class Employee:

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


employee = Employee(
    name="Ahmed",
    department="Sales",
    salary=75000
)

print(employee.name)
print(employee.department)
print(employee.salary)
Output
Ahmed
Sales
75000

Keyword arguments can make object creation easier to read, especially when a class has several parameters.

12

Validation Inside a Constructor

A constructor can also validate data before storing it inside an object.

Python
class Product:

    def __init__(self, name, price):
        if price < 0:
            raise ValueError("Price cannot be negative.")

        self.name = name
        self.price = price


product = Product("Laptop", 85000)

print(product.name)
print(product.price)
Output
Laptop
85000

If an invalid price is supplied, the constructor can reject it before the object is fully initialized.

Connect this with Lesson 42

You already learned how raise can deliberately trigger exceptions. Constructors are a practical place to use validation rules.

13

Required vs Optional Data

A constructor can contain both required and optional parameters.

Python
class Customer:

    def __init__(self, name, email, country="Pakistan"):
        self.name = name
        self.email = email
        self.country = country


customer1 = Customer(
    "Ali",
    "ali@example.com"
)

customer2 = Customer(
    "Sara",
    "sara@example.com",
    "UAE"
)

print(customer1.country)
print(customer2.country)
Output
Pakistan
UAE
14

Constructors and Class Attributes

A class can contain both class attributes and instance attributes initialized through a constructor.

Python
class Student:

    school = "PyLearn Academy"

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


student1 = Student("Ali")
student2 = Student("Sara")

print(student1.name)
print(student2.name)

print(student1.school)
print(student2.school)
Output
Ali
Sara
PyLearn Academy
PyLearn Academy

school is a class attribute, while name is an instance attribute created for each object.

15

Constructors + Methods

A class becomes much more useful when its constructor initializes data and its methods operate on that data.

Python
class Product:

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

    def show_details(self):
        print("Product:", self.name)
        print("Price:", self.price)


product = Product("Laptop", 85000)

product.show_details()
Output
Product: Laptop
Price: 85000

This is a pattern you will use repeatedly throughout object-oriented programming:

Constructor → initializes data

Attributes → store data

Methods → perform behavior

16

Real-World Examples

Constructors are heavily used in real applications. Let's examine some practical examples.

Example 1 — Bank Account

Python
class BankAccount:

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

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


account = BankAccount("Ali", 50000)

account.show_balance()
Output
Ali
Balance: 50000

Example 2 — Employee

Python
class Employee:

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

    def show_details(self):
        print(self.name)
        print(self.department)
        print(self.salary)


employee = Employee(
    "Sara",
    "Marketing",
    90000
)

employee.show_details()

Example 3 — Ecommerce Product

Python
class Product:

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

    def is_available(self):
        return self.stock > 0


product = Product(
    "Wireless Mouse",
    2500,
    15
)

print(product.name)
print(product.is_available())
Output
Wireless Mouse
True

Real-world connection

An ecommerce application could have thousands of product objects. Each object can store its own product information while sharing the same class behavior.

17

Common Constructor Mistakes

1. Forgetting self

# Wrong
class Student:

    def __init__(name):
        self.name = name

The correct version is:

class Student:

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

2. Forgetting to use self when storing attributes

# Wrong
class Student:

    def __init__(self, name):
        name = name

The parameter does not become a persistent object attribute simply by assigning it to itself.

# Correct
class Student:

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

3. Passing the wrong number of arguments

class Student:

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


student = Student("Ali")

This produces a TypeError because the required age argument is missing.

4. Confusing self.name with name

name is the incoming parameter. self.name is the attribute stored on the object.

5. Incorrect capitalization of __init__

# Wrong
def __Init__(self):
    pass

# Correct
def __init__(self):
    pass

Python's special method name is exactly __init__.

18

Practice Exercises

Exercise 1 — Student

Create a Student class with a constructor that accepts name and age.

Exercise 2 — Product

Create a Product class with name, price, and stock attributes.

Exercise 3 — Employee

Create an Employee class that accepts name, department, and salary.

Exercise 4 — Default Value

Create a Customer class where the country defaults to Pakistan.

Exercise 5 — Keyword Arguments

Create a Book class and create an object using keyword arguments.

Exercise 6 — Validation

Create a Product class that raises a ValueError when the price is negative.

Exercise 7 — Constructor + Method

Create a Car class with a constructor and a show_details() method.

Exercise 8 — Multiple Objects

Create three employee objects using the same constructor but different values.

19

Mini Challenge — Ecommerce Product Manager

Let's combine classes, constructors, attributes, methods, and validation into one practical exercise.

Your Mission

Build a simple product-management class for an ecommerce store.

Requirements

  • Create a Product class.
  • Use a constructor.
  • Accept name, price, and stock.
  • Store them as instance attributes.
  • Reject negative prices.
  • Reject negative stock values.
  • Create a show_details() method.
  • Create at least three product objects.

Starter Code

Challenge Starter
class Product:

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

        if price < 0:
            raise ValueError("Price cannot be negative.")

        if stock < 0:
            raise ValueError("Stock cannot be negative.")

        self.name = name
        self.price = price
        self.stock = stock

    def show_details(self):
        print("Name:", self.name)
        print("Price:", self.price)
        print("Stock:", self.stock)


product1 = Product(
    "Laptop",
    85000,
    10
)

product1.show_details()

Extension Challenge

Add a method called is_available() that returns True when stock is greater than zero and False otherwise.

Think like a developer

Ask yourself: what information must every product have when it is created? Which values should be validated before allowing the object to exist?

20

Quick Knowledge Check

Test your understanding of Python constructors.

1. What is the main purpose of __init__()?

2. When is __init__() normally called?

3. What does self represent?

4. Which constructor is written correctly?

5. What does self.name = name do?

6. Which creates a Student object with the name Ali?

7. Can __init__() accept parameters?

8. What happens if a required constructor argument is missing?

9. Can constructor parameters have default values?

10. Where can validation be performed?

21

Lesson Summary

Constructors make Python classes much more practical by allowing objects to be initialized with their required information at creation time.

Key Takeaways

  • __init__() is used to initialize object attributes.
  • It runs automatically when an object is initialized.
  • self refers to the current object.
  • Constructor parameters allow objects to receive data during creation.
  • Parameters can have default values.
  • Keyword arguments can make object creation clearer.
  • Constructors can validate incoming data.
  • Constructors and methods work together to create useful classes.

What's next?

In the next lesson, we move deeper into object-oriented programming and learn how one class can inherit attributes and behavior from another class.

That's where we begin Python Inheritance.

Ready for the next step?

Complete this lesson once you are comfortable using constructors and initializing Python objects.