Constructor in Python. Topic 56

Constractors In Python. Topic 55

What Is Constructors?

Constractor is a special method, that initializes the object of a class. Its name is __init__. When we create a new object, the constructor calls automatically, and the object gets the initial values.

If you don’t know what is class and how it works, I already talked about this topic. Check it now.

Why Use Constructor?

Object Initialization: The constructor helps to set the object in its initial state.

Default Values: Default values can also be assigned to the constructor. If any values are not provided these default values will be used. Constructor in Python. Topic 56

Explanation Of Constructor:

Imagine you’re a chef and you have a pizza recipe(class). The constructor is like setting up everything before making a pizza. It decides the size of the pizza, what toppings will be included, and what type of crust will be used. Let’s see through an example: In this example, we use __int__ function. Before knowing what is actually, just think __init__ is a special name of a function. We will see after this example, what is __init__.

class Pizza:
    def __init__(self, size, toppings, crust_type="Regular"):
        self.size = size
        self.toppings = toppings
        self.crust_type = crust_type

    def display_info(self):
        print(f"Pizza Details:\nSize: {self.size}\nToppings: {', '.join(self.toppings)}\nCrust: {self.crust_type}\n")

# Customer 1
pizza1 = Pizza("Large", ["Cheese", "Pepperoni", "Mushrooms"], "Thin")
pizza1.display_info()

# Customer 2
pizza2 = Pizza("Medium", ["Chicken", "Bell Peppers"])
pizza2.display_info()

In this story,

  •  __init__ is like a chef deciding the size, toppings, and crust type for each pizza.
  • When new customers(objects) come and order the pizza(create a new object), the chef ensures that pizzas are made according to their specifications.

I hope you understand this analogy. If there are any doubts comment below with your email. I will contact with you.

‘display_info’ is like serving the pizza, Showing the customer what they have ordered.

The Output Of This Code Will Be:

Python
Pizza Details:
Size: Large
Toppings: Cheese, Pepperoni, Mushrooms
Crust: Thin

Pizza Details:
Size: Medium
Toppings: Chicken, Bell Peppers
Crust: Regular

Now the biggest question is, what __init__ do? I will see through an easy example. First I will give an example without __init__ function. Let’s see.

class RectangleWithoutInit:
    def set_dimensions(self, length, width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return self.length * self.width

    def display_info(self):
        area = self.calculate_area()
        print(f"Rectangle Information:\nLength: {self.length}\nWidth: {self.width}\nArea: {area}\n")

# Using class without __init__
rectangle1 = RectangleWithoutInit()
rectangle1.set_dimensions(5, 3)
rectangle1.display_info()

rectangle2 = RectangleWithoutInit()
rectangle2.set_dimensions(7, 4)
rectangle2.display_info()

In this program, We used the set_dimensions method to set the length and width. Whenever create an object, (RectangleWithSize()), we have to call the set_dimensions method separately.

The Output Of This Code Will Be:

Python
Rectangle Information:
Length: 5
Width: 3
Area: 15

Rectangle Information:
Length: 7
Width: 4
Area: 28

Now see how we can do this same program with __init__.

Python
class RectangleWithInit:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return self.length * self.width

    def display_info(self):
        area = self.calculate_area()
        print(f"Rectangle Information:\nLength: {self.length}\nWidth: {self.width}\nArea: {area}\n")

# Using class with __init__
rectangle1 = RectangleWithInit(5, 3)
rectangle1.display_info()

rectangle2 = RectangleWithInit(7, 4)
rectangle2.display_info()

__init__ method automatically called when creating an object. When we create an object, at the same time we provide the values of height, and width like this (RectangleWithInit(5, 3)). The object becomes ready after being initialized with the __init__ method.

The Output Of This Code Will Be:

Python
Rectangle Information:
Length: 5
Width: 3
Area: 15

Rectangle Information:
Length: 7
Width: 4
Area: 28

Problem Without __init__ :

  • Without __init__ , the method has to be called separately every time, which makes the code very long. Even after the object is created, the attributes have to be set manually.

Benifits Of Using __init__:

  • The code is short and clean because the values are set as soon as the object is created.
  • Automatic initialization improves the readability and maintainability of the code.
  • I hope you understand this example, what are the benefits of __init__.

Let’s Solve Some Questions:

Rectangle Class: Define a Python class named Rectangle with attributes length and width. Create a constructor (__init__) to initialize these attributes. Include a method to calculate and return the area of the rectangle.

Person Class: Create a Python class Person with attributes name and age. Implement a constructor to initialize these attributes. Include a method to display the person’s information

Bank Account Class: Implement a Python class BankAccount with attributes account_number and balance. Include a constructor to initialize these attributes. Create two instances of the class and display their account information.

Tricky Questions:

Inheritance with Constructors: Define a base class Vehicle with a constructor. Derive two classes Car and Bike from Vehicle, each with their own constructors. Ensure that the constructor of the base class is also called when an object of the derived class is created.

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog