@staticmethod Function Decorator


Python - @staticmethod

Python @staticmethod function decorator is used to transform a method into a static method.

In this tutorial, you will learn the syntax of @staticmethod function decorator, and then its usage with the help of example programs.

Syntax

The syntax of @staticmethod function decorator is

class MyClass:
    @staticmethod
    def f(arg1, arg2, argN): ...

A static method can be called on the class, on an instance of class, or just as a regular function.

Examples

1. Call static method on the class

In the following program, we define a class MyClass, with a static method printMessage(). We shall call this static method on the class.

Python Program

class MyClass:
    @staticmethod
    def printMessage():
        print('Hello World!')

MyClass.printMessage()

Output

Hello World!

2. Call static method on the instance of a class

In the following program, we define a class MyClass, with a static method printMessage(). We shall create an instance of this class, and then call the static method on the instance.

Python Program

class MyClass:
    @staticmethod
    def printMessage():
        print('Hello World!')

obj = MyClass()
obj.printMessage()

Output

Hello World!

Summary

In this tutorial of Python Examples, we learned the syntax of @staticmethod function decorator, and how to transform a class method into a static method, with the help of examples.