Python __init__() method

Python __init__() method (Constructor)

A constructor is a special function in a class that is called when a new object is created from that class. It is used to initialize the object with specific values when the object is created.
In Python, constructors are defined using the __init__() method, and they can take parameters to initialize attributes (similar to how they work in C#).
The __init__() method acts as the constructor in Python. When you create an object of the class, Python automatically calls this method to initialize the class.

Syntax:
class ClassName:
def __init__(self, parameters):
# Initialization code goes here

self parameter:
self helps keep track of each individual object so Python knows exactly which object to work with.The self parameter in the __init__ method (and in any method of a class) in Python refers to the instance (object) of the class itself. When you create an object from a class, self gives you access to the attributes and methods of that specific object.

Let us understand this with an example:
Think of a class in Python like a blueprint of a car. The object is the actual car that you make using that blueprint. Now, when you make multiple cars (creates multiple objects) using the same blueprint(class), each car can have its own unique specifications.
In Python, self is like a way of keeping track of each individual car (or object). It helps the blueprint (class) know which car (object) it’s working with at any given time.

Example:
In this example, we add two parameters to the constructor: model_name and color_name. When we create a Car object, we pass the values for these parameters to initialize the model and color fields.

class Car:
def __init__(self, model_name, color_name):
self.model = model_name # Initialize the model
self.color = color_name # Initialize the color

def drive(self):
print(f”The {self.color} {self.model} car is driving…”)

# Creating objects with parameters passed to the constructor
car1 = Car(“Toyota”, “Blue”)
car2 = Car(“BMW”, “Red”)

# Calling the drive method
car1.drive() # Output: The Blue Toyota car is driving…
car2.drive() # Output: The Red BMW car is driving…

Code Explanation:

    1. Class Definition

class Car:

This defines the Car class

2. __init__() method (Constructor):

 def __init__(self, model_name, color_name):

This is the constructor. It takes model_name and color_name as parameters and assigns them to the object’s model and color attributes.

        self.model = model_name  # Initialize the model

This line initializes the model attribute with the value passed to the model_name parameter.

3. Methods (Actions):

 def drive(self):

This method prints the message with the car’s color and model.

4. Creating objects:

car1 = Car(“Toyota”, “Blue”)

This creates a Car object with model_name = “Toyota” and color_name = “Blue”.

5. Using methods of the car objects:

car1.drive()  # Output: The Blue Toyota car is driving…

This calls the drive() method for car1 and prints the message: “The Blue Toyota car is driving…”.

car2.drive()  # Output: The Red BMW car is driving…

This calls the drive() method for car2 and prints the message: “The Red BMW car is driving…”.

Why are we using __init__()? What difference does it make?

Without __init__() method With __init__() method
class Car:
def drive(self):
print(f”The {self.color}
{self.model} car is driving…”)
# Create object
car1 = Car()
# Manually set attributes after
object creation
car1.model = “Toyota”
car1.color = “Blue”
# Call the method
car1.drive()
# Output: The Blue Toyota car is driving…
class Car:
def __init__(self, model_name,
color_name):
self.model = model_name
self.color = color_name
def drive(self):
print(f”The {self.color}
{self.model} car is driving…”)
# Create object and initialize
#attributes using the
constructor car1 = Car(“Toyota”, “Blue”)
# Call the method
car1.drive()
# Output: The Blue Toyota car is driving…
For e.g. if we have to make 1000
cars then, we will have to
car1.model = “Toyota”
car1.color = “Blue”
car2.model = “Toyota”
car2.color = “Red”
car3.model = “Toyota”
car3.color = “Green”
.
.
.
car1000.model = “Toyota”
car1000.color = “White”
For e.g.
car1 = Car(“Toyota”, “Blue”)
car2 = Car(“Toyota”, “Red”)
car3 = Car(“Toyota”, “Green”)




car1000 = Car(“Toyota”, “White”)

Without __init__(), You have to first create the object and then you have to define attributes to the object..
With __init__(), objects and attributes can be created and defined in one single line (car1 = Car(“Toyota”, “Blue”)). This makes the object creation process more reliable, less error-prone and we need to write less lines of code comparatively.

Types of __init__ Methods:
1. Default __init__ Method:
   This type of __init__ doesn’t accept any arguments apart from self. It is used when no additional data is needed to
   initialize the object.
Example:

class Person:
   def __init__(self):
      self.name = “John”
      self.age = 30
p1 = Person()
print(p1.name) # Output: John
print(p1.age) # Output: 30

2. Parameterized __init__ Method:
This __init__ method accepts parameters in addition to self, allowing you to pass values when creating the object to initialize its attributes (name, age).
In the below example, we can define different values to attributes of different objects
(p1, p2).
Example:

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

p1 = Person(“Alice”, 25)
p2 = Person(“Bob”, 20)

print(p1.name) # Output: Alice
print(p2.name) # Output: Bob

print(p1.age) # Output: 25

3. Default Values in __init__ Method:
You can provide default values for some or all of the parameters in the __init__ method. If there are no parameters in the object, then default value will be taken (John, 30)
Example:

class Person:
def __init__(self, name=”John”, age=30):
self.name = name
self.age = age

p1 = Person() # Uses default values
p2 = Person(“Alice”, 25) # Uses provided values
p3 = Person()
print(p1.name, p1.age) # Output: John 30
print(p2.name, p2.age) # Output: Alice 25
print(p3.name, p3.age) # Output: John 30

Task:
1. Basic __init__() method:
Create a class named Employee with the following properties:
Name
Id
Salary
Implement an __init__() method that initializes these properties.

Object Name ID Salary
emp1 John 1 10000

Date:
Create an object of the Employee class in the main method, initialize it using the __init__() method, and print the properties.
Output:
John’s ID is 1 and Salary is 10000

2. Parameterized __init__() method:
Create a class named Product with the following properties:
ProductName
Category
Price

Object Product Name Category Price
obj1 Butter Dairy 100
obj2 Potato Vegetable 20

Date:
Implement a parameterized __init__() method that takes arguments to initialize these properties.
Create an object of the Product class in the main method, initialize it using the parameterized __init__() method, and print the properties.

Output:
Product Name: Butter Category: Dairy Price: 100
Product Name: Potato Category: Vegetable Price: 20

3. Default and Parameterized __init__() method:
Create a class named Student with the following properties:
Name
RollNumber
Course
Initialize default value of course as ‘Basic’ if not mentioned

Object Name RollNo Course
obj1 Jane 1 Special
obj2 John 2 Basic (By default)

Date:
Print these values

Output:
Name: Jane RollNumber: 1 Course: Special
Name: John RollNumber: 2 Course: Basic

Course Video

YouTube Reference :