Python Instance Methods Tutorial

  • Post author:
  • Post category:Python

In this section, we will learn about instance methods in Python.

Note: we’re assuming you’re familiar with the class and objects in general.

What is Python Instance Method?

A regular method that we create in a class and it takes the keyword `self` as its first parameter is called an instance method.

We call them instance method because they are designed to be used with instances (objects) of a class.

Also, these methods are capable of accessing the objects that invoked them (using the self-keyword).

Example: creating instance method in python

class Parent: 

    def __init__ (self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        
    def instanceMethod(self):
        print(f"This is an instance method!")


parent1 = Parent("John","Doe")

parent1.instanceMethod()

Output:

This is an instance method!

Example: accessing instance attributes with instance methods in python

class Parent: 

    def __init__ (self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        
    def printFullName(self):
        print(f"{self.firstName} {self.lastName}")


parent1 = Parent("John","Doe")

parent1.printFullName()

Output:

John Doe

More to Read:

Python Class Methods

Python Static Method

Leave a Reply