Introduction

In this tutorial, we will be focusing on instance methods, which are a crucial aspect of OOP in Python. Instance methods are special functions defined within the class and operate on specific instances of that class. We will explore how instance methods work in Python and demonstrate how they can be used to create dynamic and reusable code. By the end of this tutorial, you'll have a solid understanding of instance methods in Python and how they can be leveraged to create more efficient code.

Table of Contents :

  • Instance methods
  • Defining an instance method
  • Accessing an instance method 
  • Code Sample for using instance methods
  • Add new instance method dynamically 
  • Deleting instance methods dynamically
    • Using del keyword
    • Using delattr function

Instance methods :

  • The instance methods are methods that are attached to the objects of the class.
  • The instance methods are used to access and process instance variables.
  • By default, any method created inside a class is an instance method.
  • If we want to define a class method or static method, we need to explicitly indicate this.
  • The  self  keyword is the first parameter of an instance method.
  • The  self  keyword refers to the current object.
  • The  self   keyword is used to access the instance variables attached to the current object.
  • Note # : We can use any other name instead of self for the first parameter, but it is advised that we follow this convention.
  • Instance methods can modify class variables as well. The syntax for this is :   self.__class__ attribute  

Defining an instance method :

  • The syntax of defining an instance method is same as defining regular functions except that the first parameter in case of instance methods is always self.
  • The basic syntax of defining instance methods is  :

def method_name(self, arg):
   # method body
 
 

Accessing an instance method :

  • Instance methods can be accessed :
    • using the object name and dot operator.
    • using the self keyword and dot operator.
  • The basic syntax of using an instance method is :  object_name.instance_method_name 

Code Sample for using instance methods :

  • Below we have a code sample which shows how we can define and access instance methods of a class.
  • In the code sample  calc_salary  and   print_details  are two instance methods which can access and process the instance variables of the class  Employee 
  • The instance method   calc_salary  creates a new instance variable  salary  which was not defined and initialized in the  __init__ method.
  • Code Sample : 

class Employee:
    def __init__(self, emp_name, emp_id, emp_desig, basic_salary):
        # data members (instance variables  - name, id and desig)
        self.name = emp_name
        self.id = emp_id
        self.desig = emp_desig
        self.basic_sal = basic_salary

    def calc_salary(self, incr_rate):
        self.salary = self.basic_sal + self.basic_sal * incr_rate

    def print_details(self):
        print(f"Name of employee = {self.name}")
        print(f"ID of employee = {self.id}")
        print(f"Designation of employee = {self.desig}")
        print(f"Salary of employee = {self.salary}")
        print()


# Creating Employee objects
emp_1 = Employee("Steve", "k2591", "Manager", 50000)
emp_2 = Employee("Rob", "k2586", "Tech Lead", 40000)

# Calculating Salary for the Employees
emp_1.calc_salary(5.2)
emp_2.calc_salary(4.5)

# Printing details for employees
emp_1.print_details()
emp_2.print_details()


# Output
# Name of employee = Steve
# ID of employee = k2591
# Designation of employee = Manager
# Salary of employee = 310000.0

# Name of employee = Rob
# ID of employee = k2586
# Designation of employee = Tech Lead
# Salary of employee = 220000.0


Add new instance method dynamically :

  • In Python we can add new instance method to an object at runtime.
  • When we add a new instance method to an object, this new instance method is not available to the remaining objects.
  • Adding a new method at runtime might be necessary in some scenarios like :
    • We do not have access to the code of the class due to some physical or logical reason.
    • We do not want to change the structure of the original class as it is being used by other coders as well.
  • Follow the steps below to add a new instance method dynamically :
    • import a module called types using the construct :  import types 
    • define a new function that we want to add to the class.
    • use the  MethodType()  function of the types module
    • Pass two arguments to the  MethodType()  function : 
      • The first argument is the name of the new function.
      • The second argument is the name of the object to which new function is to be added.
  • Code Sample : 

import types

class Employee:
    def __init__(self, emp_name, emp_id, emp_desig):
        # data members (instance variables  - name, id and desig)
        self.name = emp_name
        self.id = emp_id
        self.desig = emp_desig

    def print_details(self):
        print(f"Name of employee = {self.name}")
        print(f"ID of employee = {self.id}")
        print(f"Designation of employee = {self.desig}")
        print()


emp_1 = Employee("Steve", "k2591", "Manager")
emp_1.print_details()


# Defining the function that we want to add to object
def communicate(self, email):
    print(f"Email Id of employee : ", email)


# Adding the function to the object emp_1
emp_1.communicate = types.MethodType(communicate, emp_1)  

# Calling the newly added function
emp_1.communicate("abc@xyz.com") 


# Output
# Name of employee = Steve
# ID of employee = k2591
# Designation of employee = Manager

# Email Id of employee :  abc@xyz.com


 

Deleting instance methods dynamically

  • We can delete an instance method of an object using :
    • del keyword
    • delattr() function

Using del keyword

  • We can delete an instance method by using  del  keyword.
  • Code Sample : 

class Employee:
    def __init__(self, emp_name, emp_id, emp_desig, basic_salary):
        # data members (instance variables  - name, id and desig)
        self.name = emp_name
        self.id = emp_id
        self.desig = emp_desig
        self.basic_sal = basic_salary

    def calc_salary(self, incr_rate):
        self.salary = self.basic_sal + self.basic_sal * incr_rate

    def print_details(self):
        print(f"Name of employee = {self.name}")
        print(f"ID of employee = {self.id}")
        print(f"Designation of employee = {self.desig}")
        print(f"Salary of employee = {self.salary}")
        print()


emp_1 = Employee("Steve", "k2591", "Manager", 50000)
del emp_1.calc_salary
emp_1.calc_salary(5.2)

# Output
# AttributeError: calc_salary


Using delattr() function

  • We can delete an instance method by using  delattr()  function.
  •  delattr()  function takes two arguments :
    • the object whose method needs to be deleted
    • the name of the instance method that we want to delete
  • Code Sample : 

class Employee:
    def __init__(self, emp_name, emp_id, emp_desig, basic_salary):
        # data members (instance variables  - name, id and desig)
        self.name = emp_name
        self.id = emp_id
        self.desig = emp_desig
        self.basic_sal = basic_salary

    def calc_salary(self, incr_rate):
        self.salary = self.basic_sal + self.basic_sal * incr_rate

    def print_details(self):
        print(f"Name of employee = {self.name}")
        print(f"ID of employee = {self.id}")
        print(f"Designation of employee = {self.desig}")
        print(f"Salary of employee = {self.salary}")
        print()


emp_1 = Employee("Steve", "k2591", "Manager", 50000)
delattr(emp_1, "calc_salary")
emp_1.calc_salary(5.2)

# Output
# AttributeError: calc_salary


Prev. Tutorial : Class variables

Next Tutorial : Class methods