Python Program on __init__() Function

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Python’s object-oriented paradigm is built on the concept of classes and instances, offering a powerful way to structure code and encapsulate data. In this exploration, we delve into the code snippet that exemplifies the utilization of the ‘self’ variable within a Python class. By creating instances of the class and employing the ‘self’ variable, we unlock the ability to manage individualized data for each instance.

This article navigates through the intricacies of the ‘self’ variable, showcasing its role in initializing, accessing, and representing instance-specific attributes.

Prerequisites

  • Basics of object-oriented programming (OOP)
  • Familiarity with Python syntax and class structure
  • Understanding of instance variables and methods in Python classes
  • Knowledge of string formatting in Python

Topic Explanation

The provided code introduces the ‘Test’ class, featuring an ‘init’ method that initializes three instance variables: ‘rno,’ ‘name,’ and ‘clgname.’ The essence of the ‘self’ variable becomes apparent here, as it binds these variables to the instance of the class. When instances ‘T1’ and ‘T2’ are created, the ‘init’ method is invoked for each, setting their unique attributes. The ‘display’ method, utilizing ‘self,’ then prints these attributes for each instance, demonstrating the instance-specific nature of the data.

Furthermore, the ‘str’ method is defined within the class, showcasing another facet of the ‘self’ variable. This method provides a string representation of the instance, formatting the output to display the roll number, name, and college name. When ‘print(T1)’ and ‘print(T2)’ are executed, the ‘str’ method is implicitly called, offering a concise and informative representation of the instances’ data. This underscores the versatility of the ‘self’ variable in not only accessing but also customizing how instances present themselves.

Program Code:

# Use of Self Variable in Python
class Test:
    def __init__(self):
        # Initializing instance variables using the constructor method
        print("This is init method of class")
        self.rno = 101       # Initializing roll number
        self.name = "Vivek"  # Initializing name
        self.clgname = "Data Flair Indore"  # Initializing college name

    def display(self):
        # Method to display instance variables
        print(self.rno)
        print(self.name)
        print(self.clgname)

    def __str__(self):
        # Using % formatting
        return "Roll No= %s Name= %s College Name=%s" % (self.rno, self.name, self.clgname)

# Creating instances of the Test class
T1 = Test()
T2 = Test()

# Displaying the custom string representation of the objects
print(T1)
print(T2)

Output:

This is init method of class
This is init method of class
Roll No= 101 Name= Vivek College Name=Data Flair Indore
Roll No= 101 Name= Vivek College Name=Data Flair Indore

Code Explanation:

  • “This is init method of class” is printed twice because the init() method prints this string
    It gets printed twice because init() is called both when the Test instance T1 is created, and when the Child instance C1 is created
  • “Roll No= 101 Name= Vivek College Name=Data Flair Indore” is printed twice, once when T1.displaydata() is called, and again when C1.displaydata() is called
  • The roll no 101, name Vivek, and college name Data Flair Indore are printed because they were assigned to self in the init() method
  • When displaydata() is called on T1, it prints out the values assigned to self for that instance
  • Similarly when displaydata() is called on C1, it prints out the values assigned to self for that instance
  • So the self variable allows each object instance to store state that is unique to that particular instance
    And self allows methods like displaydata() to access the state of the instance they are called on, to display values specific to that object

Summary

In conclusion, the ‘self’ variable in Python classes is not just a syntactic necessity but a powerful tool that enables the creation of dynamic, individualized instances. Through the provided code, we witnessed how ‘self’ ensures the uniqueness of instance attributes and how it enhances the representation of instances via the ‘str’ method. This article aimed to demystify the role of ‘self’ in creating more intuitive and versatile Python classes, showcasing its impact on both instance creation and user-friendly outputs. As Python remains a language valued for its simplicity and readability, understanding the nuances of ‘self’ contributes to writing more robust and expressive code.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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