Skip to content

Python static method | staticmethod() decorator – Example

  • by

Using staticmethod() or @staticmethod can static method in Python. The static methods cannot modify the state of an object as they are not bound to it.

Python static method examples

Simple example code.

Using staticmethod()

The @staticmethod is a built-in decorator that defines a static method in the class.

class Calculator:

    def add(a, b):
        return a + b


# create add static method
Calculator.add = staticmethod(Calculator.add)

print('Product:', Calculator.addNumbers(15, 45))

Output:

Python static method

Using @staticmethod

Using @staticmethod annotation is a much better way to create a static method.

class Calculator:

    # create addNumbers static method
    @staticmethod
    def multi(x, y):
        return x * y


print('Product:', Calculator.multi(15, 45))

Output: 675

Is it possible to have static methods in Python?

Answer: Yes Python has a static method concept and you can create it by using the staticmethod decorator, it could call without initializing a class. There are very few situations where static methods are necessary for Python code.

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print(x)


MyClass.the_static_method(2)

Output: 2

Do comment if you have any doubts or suggestions on this Python method tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading