Menu Close

Instance method in Python

In this Python guide, we will go through the Python instance method along with examples. The instance method in Python is a normal method that is used to access the unique data of their instance.

In the previous tutorial, we have seen an abstract class that is used to create a blueprint for another class.

What is the instance method in Python?

Instance method in Python is a very common type of method. These are so-called because they can access the unique data of their instance.

The instance method must have a self parameter as the first argument but sometimes we don’t need to pass. Inside any instance method, the self parameter is used to access any properties and methods that reside in class. You can’t access them without using a self parameter.

You have to remember some points when you want to work with instance methid in Python.

  • The Python instance method takes self as the first parameter that represents the object of the class.
  • The instance method can modify the state of the instance.
  • An instance method can not call using the class name but if you want to call an instance method using the class name, Then first you have created an object and then pass in the instance method. You can see the below example for a better understanding.

Example:

class Student:
	def __init__(self, name, age):
		self.name = name
		self.age = age
		
	#instance method
	def printName(self):
		print("My name is:- {}".format(self.name))
		
	#instance method
	def printAge(self):

		print("My age is:- {}".format(self.age))
		


#Create the object
obj = Student('Jain', 30)

#call instance method using class name
Student.printName(obj)
Student.printAge(obj)

Output

My name is:- Pankaj
My age is:- 25

If we have two objects and each created using the Same class Then each instance has its own properties.

Example:

class Student:
	def __init__(self, name, age):
		self.name = name
		self.age = age
		
	#instance method
	def printName(self):
		print("My name is:- {}".format(self.name))
		
	#instance method
	def printAge(self):
		print("My age is:- {}".format(self.age))
		

s1 = Student('Vishajit', 22)
s1.printName()
s1.printAge()

print("---------")

s2 = Student('Pankaj', 25)
s2.printName()
s2.printAge()

Output

My name is:- Vishajit
My age is:- 22
---------
My name is:- Pankaj
My age is:- 25

Conclusion

In this article, you have learned all about the instance method in Python along with examples. Instance method in Python should have a self parameter as a first parameter but you can change it.

Python instance method is the most common type of method that gives information of each instance.

If this article helped you. Please share it keep visiting for further Python tutorials.

For more information:- Click Here

Happy Coding
~ Vishvajit Rao

Python set() function
Python setattr() function

Related Posts