Class Method vs Static Method vs Instance Method in Python
Last Updated :
12 Mar, 2024
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help of examples in Python.
Class Method in Python
Class methods are associated with the class rather than instances. They are defined using the @classmethod
decorator and take the class itself as the first parameter, usually named cls
. Class methods are useful for tasks that involve the class rather than the instance, such as creating class-specific behaviors or modifying class-level attributes.
Syntax Python Class Method
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
fun: function that needs to be converted into a class method
returns: a class method for function.
In this example, the MyClass
defines a class variable class_variable
, and the class_method
is a class method that increments this variable. When calling the method with different values, it updates and returns the modified class variable. Instances obj1
and obj2
have their own instance_variable
.
Python3
class MyClass:
class_variable = 0
def __init__(self, value):
self.instance_variable = value
@classmethod
def class_method(cls, x):
cls.class_variable += x
return cls.class_variable
# Creating instances of the class
obj1 = MyClass(5)
obj2 = MyClass(10)
# Calling the class method
print(MyClass.class_method(3)) # Output: 3
print(MyClass.class_method(7)) # Output: 10
Static Method in Python
Static methods, as the name suggests, are not bound to either the class or its instances. They are defined using the @staticmethod
decorator and do not take a reference to the instance or the class as their first parameter. Static methods are essentially regular functions within the class namespace and are useful for tasks that do not depend on instance-specific or class-specific data.
Syntax Python Static Method
class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
returns: a static method for function fun.
In this example, the MathOperations
class features static methods add
and subtract
for performing basic arithmetic operations. These methods can be directly invoked on the class without creating an instance, providing a convenient and state-independent way to perform mathematical operations.
Python3
class MathOperations:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def subtract(x, y):
return x - y
# Using static methods without creating an instance
print(MathOperations.add(5, 3)) # Output: 8
print(MathOperations.subtract(10, 4)) # Output: 6
Instance Method in Python
Instance methods are the most common type of methods in Python classes. They are associated with instances of a class and operate on the instance's data. When defining an instance method, the method's first parameter is typically named self
, which refers to the instance calling the method. This allows the method to access and manipulate the instance's attributes.
Syntax Instance Method
class MyClass:
def instance_method(self, arg1, arg2, ...):
# Instance method logic here
pass
In this example, the Person
class defines an instance method introduce
which returns a formatted introduction based on the instance's name
and age
attributes. The instance person1
is created with the name "Kishan" and age 20, and invoking the introduce
method prints a personalized introduction for that instance. Note that there's a small typo in the comment mentioning the age; it should be 20 instead of 30.
Python3
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old."
# Creating an instance of the class
person1 = Person("Kishan", 20)
# Calling the instance method
print(person1.introduce()) # Output: Hi, I'm Kishan and I'm 30 years old.
Python Class Method Vs. Static Method Vs. Instance Method
Aspect
| Class Method
| Static Method
| Instance Method
|
---|
Definition
| A method bound to the class itself, defined with "@classmethod"
| A method that does not receive an implicit first argument ('self' or 'cls'), defined with "@staticmethod"
| A method defined within a class, taking `self` as the first parameter, representing the instance.
|
---|
Access
| Can access class attributes and modify them.
| Cannot access or modify class or instance attributes.
| Can access and modify instance attributes.
|
---|
First Argument
| Receives 'cls' as the first argument representing the class.
| No implicit first argument is passed to the method.
| Receives `self` as the first argument representing the instance.
|
---|
Usage
| Often used for operations that modify or interact with class-level data.
| Typically used for utility functions that don't depend on instance or class state.
| Commonly used for operations specific to individual instances.
|
---|
Inheritance
| Can be overridden in subclasses, with 'cls' referring to the subclass.
| Can be called directly via the class or subclass, but not overridden.
| Can be overridden in subclasses, with 'self' referring to the subclass instance.
|
---|
Access Modifier
| Typically used when the method needs access to class-level data.
| Suitable when the method doesn't rely on instance or class attributes.
| Preferred when the method operates on instance-specific attributes.
|
---|
Example Use
| Calculating statistics across all instances of a class.
| Formatting dates, performing mathematical operations.
| Returning information specific to an instance, like its attributes.
|
---|
Usefulness
| Useful when dealing with class-level functionality and shared attributes.
| Handy for standalone functions related to the class but not dependent on its state.
| Essential for modifying and accessing instance attributes and behaviors.
|
---|
Conclusion
In conclusion, we learn about the three commonly used methods in python, which are class method, static method and instance method. we also looked at how each of them work and how they are different from one another by looking at examples of programs with their code as well as outputs and a difference table that tells the difference between these 3 methods. you can also find some articles which are related to the methods in python programming below.
Similar Reads
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated
5 min read
Method resolution order in Python Inheritance
MRO stands for Method Resolution Order. It is the order in which Python looks for a method in a hierarchy of classes. MRO follows a specific sequence to determine which method to invoke when it encounters multiple classes with the same method name.. For Example : [GFGTABS] Python # Python program sh
6 min read
Instance method in Python
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
How to count number of instances of a class in Python?
Instances of a class mean the objects created for a particular class. A single class can have multiple objects of it. Here, we will find the count of the number of instances of a class in Python. Approach: Whenever an object is created, the constructor of that particular class is called.Constructor
1 min read
Class or Static Variables in Python
All objects share class or static variables. An instance or non-static variables are different for different objects (every object has a copy). For example, let a Computer Science Student be represented by a class CSStudent. The class may have a static variable whose value is "cse" for all objects.
9 min read
Bound, unbound, and static methods in Python
Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in de
5 min read
isinstance() method - Python
isinstance() is a built-in Python function that checks whether an object or variable is an instance of a specified type or class (or a tuple of classes), returning True if it matches and False otherwise, making it useful for type-checking and ensuring safe operations in dynamic code. Example: [GFGTA
3 min read
Accessor and Mutator methods in Python
In Python, class is a prototype for objects which is a user-defined type. It specifies and defines objects of the same type, a class includes a cluster of data and method definitions. Moreover, an object is a single instance of a class but you can create many objects from a single class.Note: For mo
3 min read
Extend Class Method in Python
In Python, class methods are a fundamental concept that allows us to define methods that are bound to the class, rather than the instance. Extending a class method refers to the process of modifying or enhancing a class method in a subclass while maintaining the functionality of the parent class. Wh
4 min read
Inheritance in Python Inner Class
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
3 min read