There is a printer class. He has 2 methods that do the same thing. The difference is that one of the methods is with the decorator @staticmethod , and the other is without. But I can call both methods without creating an instance of the class.

 class printer(): ''' Тест @staticmethod ''' def not_static_print(self, text = 'Example Text'): print(text) @staticmethod def static_print(text = 'Example Text'): print(text) # Не создаю никаких экземпляров printer.not_static_print(None, 'Emm?') printer.static_print('Something like this.') 

Just for not_static_print() I specify an instance, or rather its absence ( None )

Is there a fundamental difference in the use of these methods?

  • p = printer() p.not_static_print(None, 'Emm?') and now try calling that not_static_print with None first argument :) - gil9red
  • Kst, in your example the class has no object fields and you don’t contact them in not_static_print , and this will be possible only through self , but if you do this and pass None , then the error AttributeError: 'NoneType' object has no attribute . It is for such cases that static methods exist - they cannot work with the fields and methods of an object, but at the same time they are not made simply as functions. they are logically related to this class / type - gil9red

1 answer 1

@staticmethod used when your method has no access to what the class or object of the class is. It takes no required arguments, according to the type of the object of the class or the class itself.

In your first method, the self parameter is passed, which can be used later in the code (even though you do not use it), in the version with @staticmethod you cannot access the class or the object will not work out in any way. It is called in the same way as the usual method.

More details can be found here: https://www.programiz.com/python-programming/methods/built-in/staticmethod