Python Instance Methods with Examples

Posted in

Python Instance Methods with Examples
vinaykhatri

Vinay Khatri
Last updated on December 3, 2024

    In a Python class, we can define a method in three different ways:

    Python Instance Methods

    1. Instance Method

    Instance methods are the most used class methods. In the instance methods, the first parameter value is self which represents the object that is calling the method. The instance methods are generally used to modify and access the instance variables defined in the class.

    Example

    class A():
    
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def  show(self):   #show() is the instance method
            print('x:', self.x, "y:", self.y)

    2. Class Method

    In the class method, the first parameter value of the method is cls which represent the class itself. The class method is used to change the state of class variables.

    Example

    class A():
    
        x=2
        y=4
    
        @classmethod
        def  show(cls):   #show() is the class method
            print('x:', cls.x, "y:", cls.y)

    3. Static Method

    A static method is also bound to a class, but it is used when we do not want to make any changes or access the instance or class variables.

    Example

    class Login():
    
        def __init__(self, username, password):
            self.username = username
            self.password = password
    
        @staticmethod
        def  website():   #website() is a static method
            print("www.techgeekbuzz.com")

    All these three types of methods are used according to the requirements, and in this tutorial, we will learn what is an instance method in Python and how to create it. By the end of this tutorial, you will have a solid understanding of:

    • What are instance methods in Python
    • How to define the Instance method
    • How to call an instance method
    • How to modify instance variables inside an instance method
    • How to create instance variables in the Instance method.
    • How to dynamically add instance method to an object.
    • How to delete an Instance method dynamically.

    Instance Methods in Python

    In a class, Instance methods are those methods that use the instance variables and which first parameter value is self . There are two things to keep in mind for the instance methods

    1. An instance method is bound to the class object or instance.
    2. The instance method can only be accessed using the class object and it can modify the instance variables.

    When we work with the class in Python, the normal custom methods that we define with the first parameter value self are called the instance methods. The parameter self represents the instance or object that is calling that method, the name self is conventional not a keyword.

    How to define an Instance Method

    A class can have more than one object, and the instance variables that are defined in the class do not share between those multiple objects instead every object gets a copy of every instance variable. And with the help of instance methods, we can access and modify the instance variables for the particular objects. Defining an instance method is similar to defining a normal Python function. The only difference between a function definition and the instance method definition is the instance method defined inside the class and it always has a first parameter self .

    Steps to define an instance method

    1. Use the def keyword followed by the valid method name
    2. The method name should be all lowercase.
    3. Put parenthesis () after the method name with the self parameter.
    4. The self parameter is used to access the instance variables.

    Example

    class Employee:
    
        #initialize the instance variables using constructor
        def __init__(self, employee_code, name, salary):
            #instance variables
            self.employee_code = employee_code
            self.name = name
            self.salary = salary
    
        #instance method to access instance variables
        def detail(self):
            print("Employee Code:", self.employee_code)
            print("Employee Name:", self.employee_code)
            print("Employee Salary:", self.employee_code)

    Call an Instance Method

    In the above example, we see how can we define an instance method inside a class, now let’s see how to call it?

    • To call an instance method we first need to create an instance or object for the class.
    • After creating the object, use the dot operator . followed by the method name detail() to call method.

    Example

    Let’s extend the above example and call the detail() method for two different objects of the Employee class.

    class Employee:
    
        #initialize the instance variables using constructor
        def __init__(self, employee_code, name, salary):
            #instance variables
            self.employee_code = employee_code
            self.name = name
            self.salary = salary
    
        #instance method to access instance variables
        def detail(self):
            print("Employee Code:", self.employee_code)
            print("Employee Name:", self.name)
            print("Employee Salary:", self.salary)
    
    #object 1
    e1 = Employee('ET01', 'Raj', 64746)
    
    #object 2
    e2 = Employee('ET02', 'Kiran', 93746)
    
    #call the show instance method for e1 instance
    e1.detail()
    
    print()
    
    #call the show instance method for e2 instance
    e2.detail()

    Output

    Employee Code: ET01
    Employee Name: Raj
    Employee Salary: 64746
    
    Employee Code: ET02
    Employee Name: Kiran
    Employee Salary: 93746

    How to modify instance variables inside an instance method?

    As we can access the instance variables inside the instance method using the self , we can also update the instance variable for the particular object.

    Example

    class Employee:
    
        #initialize the instance variables using constructor
        def __init__(self, employee_code, name, salary):
            #instance variables
            self.employee_code = employee_code
            self.name = name
            self.salary = salary 
    
        def edit_name(self, new_name):
            #modify the name variable for particular object
            self.name = new_name
    
        #instance method to access instance variables
        def detail(self):
            print("Employee Code:", self.employee_code
            print("Employee Name:", self.name)
            print("Employee Salary:", self.salary)
    
    #Employee object
    e1 = Employee('ET01', 'Raj', 64746)
    
    print("Employee e1 details before modification")
    
    #call the show instance method for e1 instance
    e1.detail()
    
    print()
    
    #call the edit_name method on e1 object
    e1.edit_name("Raj Sharma")
    
    print("Employee e1 details after modification")
    
    #call the show instance method for e1 instance
    e1.detail()

    Output

    Employee e1 details before modification
    Employee Code: ET01
    Employee Name: Raj
    Employee Salary: 64746
    
    Employee e1 details after modification
    Employee Code: ET01
    Employee Name: Raj Sharma
    Employee Salary: 64746

    How to create instance variables using Instnace Method?

    Till now we were using the __init__() method to initialize instance variables for an instance. Now let’s create an instance method that will create an instance variable for a particular object or instance.

    Example

    class Employee:
        #initialize the instance variables using constructor
        def __init__(self, employee_code, name, salary):
            #instance variables
            self.employee_code = employee_code
            self.name = name
            self.salary = salary
    
        def add_age(self, age):
            #create a new instance variable for an instance
            self.age = age
    
    #Employee object
    e1 = Employee('ET01', 'Raj', 64746)
    
    #add a new insance variable for the e1 object
    e1.add_age(34)
    
    ''' We can access the instnace variables outside the class using the object name'''
    print("Employee Code:", e1.employee_code)
    print("Employee Name:", e1.name)
    print("Employee Age:", e1.age)
    print("Employee Salary:", e1.salary)

    Output

    Employee Code: ET01
    Employee Name: Raj
    Employee Age: 34
    Employee Salary: 64746

    Note: When we add a new instance variable for an object using the instance method, the newly created instance variable will only be created for that particular object and have no effects on other objects.

    How to dynamically add an instance method to an object in Python?

    By far we have been defining the instance methods inside the class body, but Python also gives us a syntax to define an instance method outside the class body. Defining the instance method outside the class is not a common scenario. Programmers rarely use this syntax, still it's in Python, and as a Python developer, you should know how to add an instance method to an object outside the class. There are two common scenarios where you may find adding an instance method dynamically for a particular object.

    1. When you have imported the class in the current file and you do not want to modify the imported class file.
    2. When you want only some specific object should have the instance method.

    To dynamically add an instance method for a particular object we can use the inbuilt types module’s MethodType() method.

    Syntax

    obj.method_name = types.MethodType(new_method, object)

    Example

    Let’s dynamically add a new instance method for one of the Employee class objects.

    import types
    
    class Employee:
    
        #initialize the instance variables using constructor
        def __init__(self, employee_code, name, salary):
            #instance variables
            self.employee_code = employee_code
            self.name = name
            self.salary = salary
    
        def add_age(self, age):
            #create a new instance variable for an instance
            self.age = age
    
    #new instance method
    def admin_access(self):
        self.admin = True
    
    #Employee object 1
    e1 = Employee('ET01', 'Raj', 64746)
    
    #Employee object 2
    e1 = Employee('ET02', 'Kiran', 43563)
    
    #add the admin_access method to e1 object
    e1.admin_access = types.MethodType(admin_access, e1)
    
    #call the admin_access on e1 employee
    e1.admin_access()
    
    print("Is e1 Admin:", e1.admin)

    Output

    Is e1 Admin: True

    Note: In the above example, only the object e1 has the instance method admin_access() , not e2 . If we try to call the admin_access on e2 object we will receive the Error 'Employee' object has no attribute 'admin_access'

    How to dynamically delete an instance method of an object in Python?

    There are two ways to delete an instance method of an object

    1. Using the del keyword
    2. Using the delattr () method

    In Python, everything is an object, and del keyword can delete any object. It can also delete the instance method defined for an object.

    Syntax

    del obj.method_name

    Example

    Let’s write a Python script that can the detail() method for an object.

    class Employee:
        #initialize the instance variables using constructor
        def __init__(self, employee_code, name, salary):
            #instance variables
            self.employee_code = employee_code
            self.name = name
            self.salary = salary
    
        #instance method to access instance variables
        def detail(self):
            print("Employee Code:", self.employee_code)
            print("Employee Name:", self.name)
            print("Employee Salary:", self.salary)
    
    #Employee object
    e1 = Employee('ET01', 'Raj', 64746)
    
    #employee detail before deleting the detail() method
    e1.detail()
    
    #delete the detail() method for e1 object
    del e1.detail
    
    #ERROR
    #employee detail after deleting the detail() method
    e1.detail()

    Output

    Employee Code: ET01
    Employee Name: Raj
    Employee Salary: 64746
    
    Traceback (most recent call last):
      File "C:\Users\admin\AppData\Local\Programs\Python\Python310\main.py", line 27, in <module>
        del e1.detail
    AttributeError: detail

    The delattr() function stands for delete attribute and using this inbuilt Python function we can also delete the instance method for a particular object.

    Syntax

    delattr(object, 'method_name')
    • The object is the instance or object name for which we want to delete the method.
    • Method_name (as a string) is the name of the method that we want to delete.

    Example

    class Employee:
        #initialize the instance variables using constructor
        def __init__(self, employee_code, name, salary):
            #instance variables
            self.employee_code = employee_code
            self.name = name
            self.salary = salary
    
        #instance method to access instance variables
        def detail(self):
            print("Employee Code:", self.employee_code)
            print("Employee Name:", self.name)
            print("Employee Salary:", self.salary)
    
    #Employee object
    e1 = Employee('ET01', 'Raj', 64746)
    
    #employee detail before deleting the detail() method
    e1.detail()
    
    #delete the detail() method for e1 object
    delattr(e1,'detail')
    
    #ERROR
    #employee detail after deleting the detail() method
    e1.detail()

    Output

    Employee Code: ET01
    Employee Name: Raj
    Employee Salary: 64746
    
    Traceback (most recent call last):
      File "C:\Users\admin\AppData\Local\Programs\Python\Python310\main.py", line 27, in <module>
        delattr(e1,'detail')
    AttributeError: detail

    Conclusion

    An Instance method is a normal method defined inside the class with the first self parameter. The Instance method is bound to the object and generally used to modify the state or access the instance variables. As Python is a dynamically typed language it allows us to add and delete instance methods for particular objects dynamically. In this python tutorial, we discussed what is a Instnace method in Python and how to define it. The first parameter name self in the instance method is conventional, it can be named as any valid identifier, and it works fine.

    People are also reading:

    Leave a Comment on this Post

    0 Comments