Home »
Python
Difference between @staticmethod and @classmethod in Python
Python @staticmethod and @classmethod: Here, we are going to learn what are the Difference between @staticmethod and @classmethod in Python?
Submitted by Sapna Deraje Radhakrishna, on November 01, 2019
The @classmethod Decorator
The @classmethod decorator is an inbuilt function decorator that gets evaluated after the function is defined. The result of the evaluation shadows the function definition. The @classmethod's first argument is always a class cls, similar to an instance method receiving self as its first argument.
Syntax:
Class ABC(object):
@classmethod
def function(cls, arg1, ...):
...
- Exists to create class methods that are passed with the actual class object within the function call.
- Bound to the class and not to an instance.
- Can modify the class state and that would be applied across all the instances.
The @staticmethod Decorator
@staticmethods, similar to class methods, are methods that are bound to class rather than its object. However, they do not require a class instance creation. So, are not dependent on the state of the object.
Syntax:
Class ABC(object):
@staticmethod
def function(arg1, arg2, ...):
...
- Bound to the class and not to an instance
- Cannot modify the class state
Comparison between @classmethod and @staticmethod
Class method |
Static method |
Takes cls as first parameter |
Needs no specific parameters |
Can access or modify the class state |
Cannot access the class state |
They must have parameters |
Knows nothing about the class state. Are similar to utility methods. |
Example implementation of @classmethod and @staticmethod
class City:
def __init__(self, zip_code, name):
self.zip_code = name
self.name = name
# a class method to create a city object.
@classmethod
def city_name(cls, zip_code, name):
return cls(zip_code, name)
# a static method to check if a city is capital or not
@staticmethod
def isCapital(city_name):
if city_name == 'bengaluru':
return True
if __name__ == '__main__':
bengaluru = City(560086, 'bengaluru')
mysuru = City.city_name(560111, 'mysuru')
print("city is {}".format(bengaluru.name))
print("city is {}".format(mysuru.name))
print("Bengaluru is capital :{}".format(City.isCapital('bengaluru')))
Output
city is bengaluru
city is mysuru
Bengaluru is capital : True
TOP Interview Coding Problems/Challenges