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

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

Explanation:

  • 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!")
        else:
            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

Related Posts

Friendly Guide Explaining Network Function Virtualization NFV And Operation

Introduction Computers talk to each other across long cables every second. In the past, companies bought heavy metal boxes for every task. One metal box stopped internet…

Read More

Easy Web Publishing Secrets For Every Creator With BlogOrbix

Introduction Great thoughts pop into our heads each day, but too many folks keep them locked inside. People fear complex computer setups, expensive bills, and ugly website…

Read More

Friendly Tools For Managing Software-Defined Networks In CloudOps

Introduction Computers talk to each other across long digital roads. In the cloud, we build these roads using clever code. People call this magic software-defined networking. CloudOps…

Read More

Bright Sky Routes And Golden Wings BestPilotsNow

Introduction Looking into the wide open sky brings pure wonder. Little children gaze up as shiny wings flash in the bright sunlight. You might want to grab…

Read More

Smart Networks Shape The Future of SDN in CloudOps

Introduction Computers talk to each other across long cables and invisible waves. We call this big network system the web. Old networks used heavy plastic boxes and…

Read More

Fantastic Open Road Vacations And Easy Trips With MotoShare Japan

Introduction Sunshine, clear skies, and open streets make travelers smile. Two wheels let you zoom past long lines of cars. You see hidden gardens that tour buses…

Read More
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x