Skip to content

Instance method in Python | Basics

  • by

The Python instance method is a method that belongs to instances of a class, not to the class itself. In Python, every object has its own copy of the instance attribute which is not shared by objects is called an Instance attribute.

Example Instance method in Python

Simple example code. Instance methods must have self as a parameter, but not needed to pass this in every time.

Inside any instance method, use self to access any data or methods that may reside in class. It will not accept them without going through self.

class Student:

    def __init__(self, id, name):
        self.id = id
        self.name = name

    def show(self):
        return self.id + " " + self.name


s1 = Student("101", "John")
print(s1.show())

Output:

Instance method in Python

What is the correct syntax for calling an instance method class in Python?

Answer: See the below example of calling an instance method.

class Student:

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def avg(self):
        return (self.a + self.b) / 2


s1 = Student(10, 20)
print(s1.avg())

Output: 15.0

Do comment if you have any doubts or suggestions on this Python basics tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading