The __init__ method in Class in Python (Part-10)

Posted by

The __init__ Method

  • Purpose: The __init__ method is a special method in Python classes that is automatically called when a new instance of the class is created. It is used for initializing the object’s attributes with specific values.
  • Syntax: The __init__ method is defined using the def keyword followed by __init__(self, ...). The self parameter is a reference to the current instance of the class and is used to access variables that belong to the class.
  • Usage:
    • Assign values to object properties.
    • Perform any other operations necessary when the object is created.
  • Example:
class Person:
    def __init__(self, name, age):
        self.name = name  # Initialize the name attribute
        self.age = age    # Initialize the age attribute

# Create an instance of the Person class
p1 = Person("John", 36)

# Access attributes
print(p1.name)  # Output: John
print(p1.age)   # Output: 36


  • Initialization: When p1 = Person("John", 36) is executed, the __init__ method is automatically called with self referencing the new object being created, name set to “John”, and age set to 36.
  • Attribute Assignment: Inside the __init__ method, self.name is set to “John” and self.age is set to 36. This means that the name and age attributes of the p1 object are now initialized with these values.
  • Accessing Attributes: After the object is created, its attributes can be accessed using the dot notation, like p1.name and p1.age.

Example 1: Car Class

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

    def display_info(self):
        print(f"Car: {self.brand} {self.model}, Year: {self.year}")

# Create instances of the Car class
car1 = Car("Ford", "Mustang", 1964)
car2 = Car("Tesla", "Model S", 2020)

# Access attributes and methods
print(car1.brand)  # Output: Ford
print(car2.year)   # Output: 2020
car1.display_info()  # Output: Car: Ford Mustang, Year: 1964
car2.display_info()  # Output: Car: Tesla Model S, Year: 2020

Example 2: Student Class

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

    def display_student(self):
        print(f"Student: {self.name}, Age: {self.age}, Grade: {self.grade}")

# Create instances of the Student class
student1 = Student("Alice", 14, "9th")
student2 = Student("Bob", 17, "12th")

# Access attributes and methods
print(student1.name)  # Output: Alice
print(student2.grade)  # Output: 12th
student1.display_student()  # Output: Student: Alice, Age: 14, Grade: 9th
student2.display_student()  # Output: Student: Bob, Age: 17, Grade: 12th

Example 3: Book Class

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

    def display_book(self):
        print(f"Book: {self.title}, Author: {self.author}, Pages: {self.pages}")

# Create instances of the Book class
book1 = Book("1984", "George Orwell", 328)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 281)

# Access attributes and methods
print(book1.title)  # Output: 1984
print(book2.author)  # Output: Harper Lee
book1.display_book()  # Output: Book: 1984, Author: George Orwell, Pages: 328
book2.display_book()  # Output: Book: To Kill a Mockingbird, Author: Harper Lee, Pages: 281

Example 4: Employee Class

class Employee:
    def __init__(self, emp_id, name, department):
        self.emp_id = emp_id
        self.name = name
        self.department = department

    def display_employee(self):
        print(f"Employee ID: {self.emp_id}, Name: {self.name}, Department: {self.department}")

# Create instances of the Employee class
emp1 = Employee(101, "John Doe", "HR")
emp2 = Employee(102, "Jane Smith", "IT")

# Access attributes and methods
print(emp1.emp_id)  # Output: 101
print(emp2.department)  # Output: IT
emp1.display_employee()  # Output: Employee ID: 101, Name: John Doe, Department: HR
emp2.display_employee()  # Output: Employee ID: 102, Name: Jane Smith, Department: IT

Example 5: Bank Account Class

class BankAccount:
    def __init__(self, account_number, owner, balance=0):
        self.account_number = account_number
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"Deposited {amount}. New balance is {self.balance}.")

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds!")
            self.balance -= amount
            print(f"Withdrew {amount}. New balance is {self.balance}.")

    def display_account(self):
        print(f"Account Number: {self.account_number}, Owner: {self.owner}, Balance: {self.balance}")

# Create instances of the BankAccount class
acc1 = BankAccount("123456", "Alice")
acc2 = BankAccount("789012", "Bob", 500)

# Access attributes and methods
print(acc1.balance)  # Output: 0
print(acc2.owner)  # Output: Bob
acc1.deposit(100)  # Output: Deposited 100. New balance is 100.
acc2.withdraw(200)  # Output: Withdrew 200. New balance is 300.
acc1.display_account()  # Output: Account Number: 123456, Owner: Alice, Balance: 100
acc2.display_account()  # Output: Account Number: 789012, Owner: Bob, Balance: 300

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x