Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Instance Methods?
2.1.
Example 1
2.2.
Python
2.3.
Example 2
2.4.
Python
3.
What are Class Methods?
3.1.
Python
4.
What are Static Methods?
4.1.
Example
4.2.
Python
5.
Difference Between Class Method, Static Method, and Instance Method-Table
6.
Frequently Asked Questions
6.1.
What is the difference between an instance method and a class method?
6.2.
What is a static method?
6.3.
What is an instance method?
6.4.
What are the two types of instance methods?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Difference Between Class Method, Static Method, and Instance Method

Author yuvatimankar
0 upvote

Introduction

Object-oriented programming (OOP), which is an adopted programming paradigm, highly emphasizes the utilization of objects for data representation and manipulation. A notable characteristic of OOP is its ability to create methods that facilitate communication with these objects. In Python, there are three categories of methods; class methods, static methods, and instance methods.

Difference between class method, static method, and an instance method

In this article, we will see the difference between class method, static method, and instance method, along with the examples. So, let's get started!

What are Instance Methods?

In object-oriented programming (OOP) an instance method refers to a method that's specific to an object rather than the entire class. It carries out a series of actions on the data or value provided by the object variable. When we utilize the instance variable within these methods, they are referred to as instance methods. These methods have the ability to modify the state of the object. To interact with an instance method, we use the "self" keyword as the parameter, which points to the object.

Example 1

Code

  • Python

Python

class Student:
   # constructor
   def __init__(self, name, subject, percentage):

       # Instance variables
       self.name = name
       self.subject = subject
       self.percentage = percentage

   # instance method to access instance variables
   def display(self):
       print(f'Name: {self.name}\nSubject: {self.subject}\nPercentage: {self.percentage}')

# Create an instance of the Student class
obj = Student('Justin', 'Science', 85.5)
obj.display()

Output:

output


Explanation

In the above code, the constructor is defined that creates the instance variable using the Python object. The method display() then accesses and shows these instance variables using the self keyword. Now, we will access and modify the instance variables in the code below.

Example 2

Code

  • Python

Python

class Student:
   # constructor
   def __init__(self, name, subject, percentage):

       # Instance variables
       self.name = name
       self.subject = subject
       self.percentage = percentage

# instance method to access instance variables
   def show(self):
       print(f'Name: {self.name}\nSubject: {self.subject}\nPercentage: {self.percentage}')

# instance method to change percentage
   def change_percentage(self, new_percentage):
       self.percentage = new_percentage

  # instance method to change subject and percentage
   def change_subject_and_percentage(self, new_subject, new_percentage):
       self.subject = new_subject
       self.percentage = new_percentage

# Create an instance of the Student class
obj = Student('Justin', 'Science', 85.5)

# Display initial details
print("Initial Student Details:")
obj.show()

# Change the subject and percentage using the instance method
new_subject = "Maths"
new_percentage = 90.0
obj.change_subject_and_percentage(new_subject, new_percentage)

# Display updated details
print("\nUpdated Student Details:")
obj.show()

Output:

output


Explanation

Based on the given example, it is evident that we successfully accessed the instance variable and made changes to its value. Subsequently, when the show() function was executed, it displayed the updated values.

What are Class Methods?

The class method is the method that is specific to the class instead of specific to the Instance. It can change the class state, which means it can modify class configuration globally. Class methods can only access the class variable. This method is used to create the factory method. 

The syntax of Class methods is different; rather than taking self parameter, they accept cls as a parameter that points to the class. It cannot change the instance state. However, the changes made by the class method affect all instances of the class. The classmethod() or @classmethod decorator defines the class methods.

Code

  • Python

Python

class Student:
   # class variable
   Fee = 75000

   def __init__(self, name, department):
       # Instance variable
       self.name = name
       self.department = department
   # instance method to access instance variable

   def show(self):
       print(f'Name: {self.name} Department: {self.department} Fee: {Student.Fee}')       
def show1(self):
       print(f'Name: {self.name} Department: {self.department} Updated Fee: {Student.get_updated_fee()}')

   @classmethod
   def Updated_fee(cls, fee):
       cls.Fee = fee
      
   @classmethod
   def get_updated_fee(cls):
       return cls.Fee
obj = Student('Justin', 'CS')
obj.show() 

Student.Updated_fee(85000)
obj.show1() 

Output:

output

Explanation

In the above code, we defined the class variable name Fee and the method Updated_fee(). The Updated_fee() function accessed the class variable Fee and used this function to modify the Fee for all the students. We have also used two functions for printing, show() and show1(), for better understanding.

What are Static Methods?

A static method is a kind of method found in a class that doesn't have access, to the class ('cls') or instance ('self') parameters. It operates on its own. Doesn't rely on any attributes or behaviors of instances or classes. To define methods, we use either the @staticmethod decorator or the staticmethod() function. While these methods are related to a class's utility functions, they function independently. Cannot alter the behavior of the class or its instances.

Example

Code

  • Python

Python

class Student:
   @staticmethod
   def sample_method(name):
         return len(name)

# Get the student's name from the user
name = input("Enter the student's name: ")

# Call the static method to count characters
name_length = Student.sample_method(name)

# Display the result
print(f"The name '{name}' has {name_length} characters.")


Output:

output

Explanation

In the above code, we have created a static method named sample_method(), which takes a student's name as a parameter and returns the number of characters in the name. The above code shows how the static method can be used to count the characters in names when called directly on the class and also when using an instance.

Note: In our compiler, give input of the name in the custom input section; otherwise, the code will not run properly.

Difference Between Class Method, Static Method, and Instance Method-Table

Aspect Class Method Instance Method Static Method
Keyword/Decorator ‘@classmethod’ No keyword or decorator needed ‘staticmethod()’ or ‘@staticmethod’
Access to  Class-level data, not instance-specific data Both instance-specific and class-level data Neither instance-specific nor class-level data
First parameter 'cls' (class itself) ‘Self’ (instance) Neither ‘cls’ nor ‘self’
Accessed through Class name Instance of the class Instance of the class or Class name
Use case When operation involves class-level data When operation involves instance-specific data When the utility function does not depend on instance/ class

Also see, Difference Between Structure and Union

Frequently Asked Questions

What is the difference between an instance method and a class method?

An instance method is created from a specific object. For running an instance method, an object should be present in memory. In contrast, a class method does not require a specific instance.

What is a static method?

A method that belongs to a class instead of an instance of a class is known as a static method. Static methods are sometimes also known as class methods.

What is an instance method?

These are the methods that needs an object of its class to be created before it can be called.

What are the two types of instance methods?

The two types of instance methods are the Accessor Method(Getters) and the Mutator Method (Setter).

Conclusion

In this article, we discussed the Difference Between Class Method, Static Method, and Instance Method. We have seen what the Class, Static, and instance methods are, along with their examples, and then we saw the difference between them in the form of a table. We hope this blog has helped you enhance your knowledge of the difference Between Class Method, Static Method, and Instance Method.  If you want to learn more, then check out our articles:


Refer to our guided paths on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must have a look at the problemsinterview experiences, and interview bundles for placement preparations.

Nevertheless, consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass