Both of these examples define a class with a static method. The only difference is that in the second case, you use the decorator @staticmethod , which clearly indicates that the method is static.
When a class has static methods, it is logical to assume that they will be called "from the class", and not from an object of this class:
class Robot: def sayHi(): print("Hi") Robot.sayHi()
But if we call the same method from the object:
robot = Robot() robot.sayHi()
Then we get an error:
Traceback (most recent call last): File ".../main.py", line 9, in <module> robot.sayHi() TypeError: sayHi() takes 0 positional arguments but 1 was given
Why it happens?
Because the robot.sayHi() call is equivalent to calling Robot.sayHi(robot) , and since this method does not accept anything, an error occurs because an object of the class is passed by an implicit first argument.
We should also mention @staticmethod from the documentation:
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: @staticmethod def f(arg1, arg2, ...): ...
The @staticmethod form is a function decorator - see the description of the function definitions for the function.
It can be called either on the class (such as Cf ()) or on an instance (such as C (). F ()). The instance is ignored except for its class.
Static methods in Python. For a more advanced concept, see classmethod () in this section.
As can be seen from the documentation, this decorator "explicitly" makes the method static. However, it can still be called using the: robot().sayHi() object, but this time there will be no error and this call will be equivalent to Robot.sayHi() - only the type of the called object is taken into account.
Robot().sayHi()- andreymal