Class method vs Static method in Python
Last Updated :
26 Jul, 2024
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 after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as an implicit first argument, just like an instance method receives the instance
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.
- A class method is a method that is bound to the class and not the object of the class.
- They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
- It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that will be applicable to all the instances.
What is the Static Method in Python?
A static method does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.
Syntax Python Static Method:
class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
returns: a static method for function fun.
Class method vs Static Method
The difference between the Class method and the static method is:
- A class method takes cls as the first parameter while a static method needs no specific parameters.
- A class method can access or modify the class state while a static method can’t access or modify it.
- In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
- We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.
When to use the class or static method?
- We generally use the class method to create factory methods. Factory methods return class objects ( similar to a constructor ) for different use cases.
- We generally use static methods to create utility functions.
How to define a class method and a static method?
To define a class method in python, we use @classmethod decorator, and to define a static method we use @staticmethod decorator.
Let us look at an example to understand the difference between both of them. Let us say we want to create a class Person. Now, python doesn’t support method overloading like C++ or Java so we use class methods to create factory methods. In the below example we use a class method to create a person object from birth year.
As explained above we use static methods to create utility functions. In the below example we use a static method to check if a person is an adult or not.
One simple Example :
class method:
Python
class MyClass:
def __init__(self, value):
self.value = value
def get_value(self):
return self.value
# Create an instance of MyClass
obj = MyClass(10)
# Call the get_value method on the instance
print(obj.get_value()) # Output: 10
Static method:-
Python
class MyClass:
def __init__(self, value):
self.value = value
@staticmethod
def get_max_value(x, y):
return max(x, y)
# Create an instance of MyClass
obj = MyClass(10)
print(MyClass.get_max_value(20, 30))
print(obj.get_max_value(20, 30))
Below is the complete Implementation
Python3
# Python program to demonstrate
# use of class method and static method.
from datetime import date
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# a class method to create a Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# a static method to check if a Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
print(person1.age)
print(person2.age)
# print the result
print(Person.isAdult(22))
Output:
21
25
True
Auxiliary Space: O(1)
Similar Reads
*args and **kwargs in Python
In Python, *args and **kwargs are used to allow functions to accept an arbitrary number of arguments. These features provide great flexibility when designing functions that need to handle a varying number of inputs. Example: [GFGTABS] Python # *args example def fun(*args): return sum(args) print(fun
4 min read
Packing and Unpacking Arguments in Python
Python provides the concept of packing and unpacking arguments, which allows us to handle variable-length arguments efficiently. This feature is useful when we donât know beforehand how many arguments will be passed to a function. Packing ArgumentsPacking allows multiple values to be combined into a
3 min read
First Class functions in Python
First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
2 min read
Python Closures
In Python, a closure is a powerful concept that allows a function to remember and access variables from its lexical scope, even when the function is executed outside that scope. Closures are closely related to nested functions and are commonly used in functional programming, event handling and callb
3 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Help function in Python
help() function in Python is a built-in function that provides information about modules, classes, functions and modules. It is useful for retrieving information on various Python objects. Example: [GFGTABS] Python help() [/GFGTABS]OutputWelcome to Python 3.13's help utility! If this is your first t
5 min read
__import__() function in Python
__import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement. It's useful in cases where the name of the needed module is know to us in the runtime only, then to import those mo
2 min read
Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
6 min read
Constructors in Python
In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Destructors in Python
Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
7 min read