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.
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))
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))
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)
Do comment if you have any doubts and suggestions on this Python method tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.