Define Static Method using @staticmethod Decorator in Python

The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn't receive any reference argument whether it is called by an instance of a class or by the class itself.

@staticmethod Characteristics

  • Declares a static method in the class.
  • It cannot have cls or self parameter.
  • The static method cannot access the class attributes or the instance attributes.
  • The static method can be called using ClassName.MethodName() and also using object.MethodName().
  • It can return an object of the class.

The following example demonstrates how to define a static method in the class:

Example: Define Static Method
class Student:
    name = 'unknown' # class attribute
    
    def __init__(self):
        self.age = 20  # instance attribute

    @staticmethod
    def tostring():
        print('Student Class')

Above, the Student class declares the tostring() method as a static method using the @staticmethod decorator. Note that it cannot have self or cls parameter.

The static method can be called using the ClassName.MethodName() or object.MethodName(), as shown below.

Example: Calling Class Method using Object
>>> Student.tostring()
'Student Class'
>>> Student().tostring() 
'Student Class'
>>> std = Student()
>>> std.tostring()
'Student Class'

The static method cannot access the class attributes or instance attributes. It will raise an error if try to do so.

Example: Static Method
class Student:
    name = 'unknown' # class attribute
    
    def __init__(self):
        self.age = 20  # instance attribute

    @staticmethod
    def tostring():
        print('name=',name,'age=',self.age)

The following will be the output when you call the above static method.

>>> Student.tostring()
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    Student.tostring()
  File "<pyshell#21>", line 7, in display
    print('name=',name,'age=',self.age)
NameError: name 'name' is not defined

@classmethod vs @staticmethod

The following table lists the difference between the class method and the static method:

@classmethod @staticmethod
Declares a class method. Declares a static method.
It can access class attributes, but not the instance attributes. It cannot access either class attributes or instance attributes.
It can be called using the ClassName.MethodName() or object.MethodName(). It can be called using the ClassName.MethodName() or object.MethodName().
It can be used to declare a factory method that returns objects of the class. It cannot return an object of the class.
Want to check how much you know Python?