Adventures in Machine Learning

Unraveling the Enigma of Python’s Instance & Class Methods

Unlocking the Mysteries of Python’s Instance and Class Methods

Python is one of the most widely used programming languages across the globe. This dynamic language makes things easier for developers by allowing them to write robust and efficient code.

One of the things that make Python unique is the ability to use instance and class methods. For those who are new to these terminologies, instance and class methods are two different ways to define functions in Python.

In this article, we will take an in-depth look at instance and class methods, their definitions, uses, and advantages.

INSTANCE METHODS IN PYTHON

Instance methods are the most common type of function defined in Python. These methods are defined inside a class and are accessed and executed through class objects.

Instance methods allow developers to access and modify the state of an object using the self parameter, which always points to an instance of the class.

Creating an Instance Method

Instance methods are created by defining a function inside a class with the self parameter as its first parameter. Every instance method of a class makes use of the self parameter, which is used to access and modify the state of an object.

For example, consider the following class:

class Student:
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no
    def show_name(self):
        print("The name of the student is: ", self.name)

In this example, we have defined a class Student that has two attributes, name and roll_no, which are initialized through the constructor __init__() method. We have also defined an instance method show_name(), which prints the name of the student.

Calling an Instance Method

Instance methods are executed by calling them through class objects using the dot operator. The self parameter is a reference to the calling object, and it is passed implicitly, so we do not need to pass it explicitly.

Consider the following example:

student1 = Student("John Doe", 1)
student1.show_name()

In this example, we have created an object student1 of the class Student. We are then calling the show_name() method, which is defined in the class.

On executing this code, the output is:

The name of the student is:  John Doe

Modifying Instance Variables inside Instance Method

Instance methods can be used to modify the state of an object. The state of an object refers to the values assigned to its attributes.

To modify the state of an object inside an instance method, we can use the update method. For example:

class Student:
    def __init__(self, name, roll_no, marks=0):
        self.name = name
        self.roll_no = roll_no
        self.marks = marks
    def add_marks(self, marks):
        self.marks += marks
        print("The updated marks of the student with roll number", self.roll_no, " is ", self.marks)

In this example, we have added a new attribute marks to the class Student.

We have also defined a new instance method add_marks() that modifies the marks of the student. This is achieved by updating the value of the marks attribute using the update method.

Creating Instance Variables in Instance Method

Instance variables are variables that are created inside a method and are only accessible within that method. To create an instance variable inside an instance method, we can simply define a new variable and assign it a value.

Consider the following example:

class Student:
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no
    def add_info(self, info):
        self.info = info
        print("The added information for the student ", self.name, " with roll number ", self.roll_no, " is: ", self.info)

In this example, we have defined a new instance method add_info(), which creates a new instance variable info and assigns it a value through a parameter. The value of this instance variable can then be accessed and printed through the method.

Dynamically Adding and Deleting Instance Methods

Python being an object-oriented programming language provides a lot of flexibility to its users. One of these is the ability to dynamically add and delete instance methods of a class.

To add an instance method dynamically, we can make use of the types module and the MethodType() function.

Consider the following example:

import types
class Student:
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no
    
def display_roll_no(self):
    print("The roll number of the student is: ", self.roll_no)

student1 = Student("John Doe", 1)
Student.display_roll_no = types.MethodType(display_roll_no, student1)
student1.display_roll_no()

In this example, we are using the types module to add a new instance method dynamically. We have created a new function display_roll_no() that takes one argument self.

We then create an object student1 of the class Student and add the new method dynamically to student1 using the MethodType() function. After that, we are calling this new method using the created object.

To delete an instance method dynamically, we make use of the del operator or the delattr() method.

Consider the following example:

class Student:
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no
    def show_name(self):
        print("The name of the student is: ", self.name)

student1 = Student("John Doe", 1)
del student1.show_name

In this example, we are deleting the instance method show_name() of the object student1 using the del operator.

CLASS METHODS IN PYTHON

Class methods are another type of function that can be defined in Python classes. These methods are accessed and executed through classes and can be used to modify or access the state of a class.

Creating a Class Method

Class methods are created by defining a function inside a class and decorating it with the @classmethod decorator. Like instance methods, class methods also take the first parameter as a reference to the class and not the instance.

Consider the following example:

class Student:
    student_count = 0
    
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no
        Student.student_count += 1
    @classmethod
    def display_count(cls):
        print("The total number of students is: ", cls.student_count)

In this example, we have defined a class method display_count() using the @classmethod decorator. This method accesses the class attribute student_count using the reference to the class.

Calling a Class Method

Class methods are executed by calling them through a class object or directly through a class name using the dot operator. Consider the following example:

student1 = Student("John Doe", 1)
student2 = Student("Alice Smith", 2)
Student.display_count()

In this example, we have created two objects of the class Student and called the class method display_count() using the class name.

Advantages and Use Cases

Class methods can be used to modify or access the state of a class, making them useful in a wide range of scenarios. Class methods can also be used as alternative constructors or to modify class attributes.

Consider the following example:

from datetime import date
class Person:
    age = 25
    
    def __init__(self, name):
        self.name = name
    @classmethod
    def from_birth_year(cls, name, birth_year):
        age = date.today().year - birth_year
        return cls(name, age)

person1 = Person("John Doe")
person2 = Person.from_birth_year("Alice Smith", 1995)

print(person1.age)
print(person2.age)

In this example, we have created a class Person and a class method from_birth_year() that creates a new object with an age attribute instead of a birth_year attribute. This method can be used as an alternative constructor and provides a lot of flexibility to the user.

SUMMARY

Instance and class methods are an essential part of good Python programming. Instance methods allow developers to access and modify object states, while class methods provide a way to access and modify class states.

Both instance and class methods come with their unique advantages and use cases. By mastering these two types of methods, developers can create efficient and robust Python programs that are both readable and maintainable.

In conclusion, understanding instance and class methods is essential for any Python developer. Instance methods allow access and modification of object states, while class methods provide a way to modify class states.

These two types of methods come with their unique advantages and use cases, and by mastering them, developers can create efficient and robust Python programs. The ability to dynamically add and delete methods adds to the flexibility and dynamism of the language.

Python’s instance and class methods have expanded functionality, and developers who understand these methods can create more organized and efficient code.

Popular Posts