class Robot: def sayHi(): print("Hi") class Robot: @staticmethod def sayHi(): print("Hi") 

What is the difference ? When calling Robot.sayHi() both work.

PS: I understand that the question is stupid, but I can not find the answer (probably I don’t know how to ask the right question)

  • A static function refers to a class, not to a specific object. Accordingly, it cannot use the data of a specific object, as well as non-static functions. More precisely, it can, but it must get itself an object for this, as opposed to a non-static function that can access the data and functions of the object in which it is called. PS: The question is good. - VladD
  • one
    The difference will be when calling Robot().sayHi() - andreymal
  • VladD, you probably thought that the class method (self) was indicated there, and not just a function in the class ****** insolor, the situation described above ****** andreymal, thanks so far this is the only difference found - Alexander Verbitsky

1 answer 1

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.