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.


    Class ABC(object):
	    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.


    Class ABC(object):
	    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. 
    def city_name(cls, zip_code, name): 
        return cls(zip_code, name) 
    # a static method to check if a city is capital or not
    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')))


city is bengaluru
city is mysuru
Bengaluru is capital : True

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.