PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python Object-Oriented Programming (OOP) » Python Instance Methods Explained With Examples

Python Instance Methods Explained With Examples

Updated on: August 28, 2021 | 4 Comments

In Python object-oriented programming, when we design a class, we use the instance methods and class methods.

Inside a Class, we can define the following two types of methods.

  • Instance methods: Used to access or modify the object state. If we use instance variables inside a method, such methods are called instance methods. It must have a self parameter to refer to the current object.
  • Class methods: Used to access or modify the class state. In method implementation, if we use only class variables, then such type of methods we should declare as a class method. The class method has a cls parameter which refers to the class.

Also, read Python Class method vs Static method vs Instance method.

After reading this article, you’ll learn:

  • How to create and call instance methods
  • how to dynamically add or delete instance methods in Python

Table of contents

  • What is Instance Methods in Python
  • Define Instance Method
  • Calling An Instance Method
  • Modify Instance Variables inside Instance Method
  • Create Instance Variables in Instance Method
  • Dynamically Add Instance Method to a Object
  • Dynamically Delete Instance Methods

What is Instance Methods in Python

If we use instance variables inside a method, such methods are called instance methods. The instance method performs a set of actions on the data/value provided by the instance variables.

  • A instance method is bound to the object of the class.
  • It can access or modify the object state by changing the value of a instance variables

When we create a class in Python, instance methods are used regularly. To work with an instance method, we use the self keyword. We use the self keyword as the first parameter to a method. The self refers to the current object.

Any method we create in a class will automatically be created as an instance method unless we explicitly tell Python that it is a class or static method.

Instance method in Python
Instance method in Python

Define Instance Method

Instance variables are not shared between objects. Instead, every object has its copy of the instance attribute. Using the instance method, we can access or modify the calling object’s attributes.

Instance methods are defined inside a class, and it is pretty similar to defining a regular function.

  • Use the def keyword to define an instance method in Python.
  • Use self as the first parameter in the instance method when defining it. The self parameter refers to the current object.
  • Using the self parameter to access or modify the current object attributes.

You may use a variable named differently for self, but it is discouraged since self is the recommended convention in Python.

Let’s see the example to create an instance method show() in the Student class to display the student details.

Example:

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

    # instance method to access instance variable
    def show(self):
        print('Name:', self.name, 'Age:', self.age)

Calling An Instance Method

We use an object and dot (.) operator to execute the block of code or action defined in the instance method.

  • First, create instance variables name and age in the Student class.
  • Next, create an instance method display() to print student name and age.
  • Next, create object of a Student class to call the instance method.

et’s see how to call an instance method show() to access the student object details such as name and age.

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

    # instance method access instance variable
    def show(self):
        print('Name:', self.name, 'Age:', self.age)

# create first object
print('First Student')
emma = Student("Jessa", 14)
# call instance method
emma.show()

# create second object
print('Second Student')
kelly = Student("Kelly", 16)
# call instance method
kelly.show()

Output:

First Student
Name: Jessa Age: 14

Second Student
Name: Kelly Age: 16

Note:

Inside any instance method, we can use self to access any data or method that reside in our class. We are unable to access it without a self parameter.

An instance method can freely access attributes and even modify the value of attributes of an object by using the self parameter.

By Using self.__class__ attribute we can access the class attributes and change the class state. Therefore instance method gives us control of changing the object as well as the class state.

Modify Instance Variables inside Instance Method

Let’s create the instance method update() method to modify the student age and roll number when student data details change.

class Student:
    def __init__(self, roll_no, name, age):
        # Instance variable
        self.roll_no = roll_no
        self.name = name
        self.age = age

    # instance method access instance variable
    def show(self):
        print('Roll Number:', self.roll_no, 'Name:', self.name, 'Age:', self.age)

    # instance method to modify instance variable
    def update(self, roll_number, age):
        self.roll_no = roll_number
        self.age = age

# create object
print('class VIII')
stud = Student(20, "Emma", 14)
# call instance method
stud.show()

# Modify instance variables
print('class IX')
stud.update(35, 15)
stud.show()

Output:

class VIII
Roll Number: 20 Name: Emma Age: 14
class IX
Roll Number: 35 Name: Emma Age: 15

Create Instance Variables in Instance Method

Till the time we used constructor to create instance attributes. But, instance attributes are not specific only to the __init__() method; they can be defined elsewhere in the class. So, let’s see how to create an instance variable inside the method.

Example:

class Student:
    def __init__(self, roll_no, name, age):
        # Instance variable
        self.roll_no = roll_no
        self.name = name
        self.age = age

    # instance method to add instance variable
    def add_marks(self, marks):
        # add new attribute to current object
        self.marks = marks

# create object
stud = Student(20, "Emma", 14)
# call instance method
stud.add_marks(75)

# display object
print('Roll Number:', stud.roll_no, 'Name:', stud.name, 'Age:', stud.age, 'Marks:', stud.marks)

Output:

Roll Number: 20 Name: Emma Age: 14 Marks: 75

Dynamically Add Instance Method to a Object

Usually, we add methods to a class body when defining a class. However, Python is a dynamic language that allows us to add or delete instance methods at runtime. Therefore, it is helpful in the following scenarios.

  • When class is in a different file, and you don’t have access to modify the class structure
  • You wanted to extend the class functionality without changing its basic structure because many systems use the same structure.

Let’s see how to add an instance method in the Student class at runtime.

Example:

We should add a method to the object, so other instances don’t have access to that method. We use the types module’s MethodType() to add a method to an object. Below is the simplest way to method to an object.

import types

class Student:
    # constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # instance method
    def show(self):
        print('Name:', self.name, 'Age:', self.age)

# create new method
def welcome(self):
    print("Hello", self.name, "Welcome to Class IX")


# create object
s1 = Student("Jessa", 15)

# Add instance method to object
s1.welcome = types.MethodType(welcome, s1)
s1.show()

# call newly added method
s1.welcome()

Output:

Name: Jessa Age: 15
Hello Jessa Welcome to Class IX

Dynamically Delete Instance Methods

We can dynamically delete the instance method from the class. In Python, there are two ways to delete method:

  • By using the del operator
  • By using delattr() method

By using the del operator

The del operator removes the instance method added by class.

Example:

In this example, we will delete an instance method named percentage() from a Student class. If you try to access it after removing it, you’ll get an Attribute Error.

class Student:
    # constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # instance method
    def show(self):
        print('Name:', self.name, 'Age:', self.age)

    # instance method
    def percentage(self, sub1, sub2):
        print('Percentage:', (sub1 + sub2) / 2)

emma = Student('Emma', 14)
emma.show()
emma.percentage(67, 62)

# Delete the method from class using del operator
del emma.percentage

# Again calling percentage() method
# It will raise error
emma.percentage(67, 62)

Output:

Name: Emma Age: 14
Percentage: 64.5

 File "/demos/oop/delete_method.py", line 21, in <module>
    del emma.percentage
AttributeError: percentage

By using the delattr() method

The delattr() is used to delete the named attribute from the object with the prior permission of the object. Use the following syntax to delete the instance method.

delattr(object, name)
  • object: the object whose attribute we want to delete.
  • name: the name of the instance method you want to delete from the object.

Example:

In this example, we will delete an instance method named percentage() from a Student class.

emma = Student('Emma', 14)
emma.show()
emma.percentage(67, 62)

# delete instance method percentage() using delattr()
delattr(emma, 'percentage')
emma.show()

# Again calling percentage() method
# It will raise error
emma.percentage(67, 62)

Filed Under: Python, Python Object-Oriented Programming (OOP)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Object-Oriented Programming (OOP)

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Object-Oriented Programming (OOP)
TweetF  sharein  shareP  Pin

Python OOP

  • Python OOP
  • Classes and Objects in Python
  • Constructors in Python
  • Python Destructors
  • Encapsulation in Python
  • Polymorphism in Python
  • Inheritance in Python
  • Python Instance Variables
  • Python Instance Methods
  • Python Class Variables
  • Python Class Method
  • Python Static Method
  • Python Class Method vs. Static Method vs. Instance Method
  • Python OOP exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com