Python | Difference between @classmethod and @staticmethod

Python | @staticmethod Vs. @classmethod: In this tutorial, we will learn about the @staticmethod and @classmethod decorators and the key differences between them with the help of examples. By Sapna Deraje Radhakrishna Last updated : June 26, 2023

Python @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

The below is the syntax of @classmethod decorator:

class ABC(object):
	@classmethod
	def function(cls, arg1, ...):
		...

Note:

  • 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.

Python @staticmethod decorator

The @staticmethod decorator, 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

The below is the syntax of @staticmethod decorator:

class ABC(object):
	@staticmethod
	def function(arg1, arg2, ...):
		...

Note:

  • Bound to the class and not to an instance
  • Cannot modify the class state

Difference between @classmethod and @staticmethod

@classmethod @staticmethod
The @classmethod takes cls as first parameter. The @staticmethod needs no specific parameters.
The @classmethod can access or modify the class state. The @staticmethod cannot access the class state.
The @classmethod must have parameters. The @staticmethod knows nothing about the class state and is similar to utility methods.

Example of @classmethod and @staticmethod decorators

Consider the below example demonstrating the difference between @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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.