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 Static Method
#calling static method    
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)


Student.tostring()   #error

@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 can return an object of the class.