Python static method | staticmethod() decorator – Example

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 and suggestions on this Python method tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.