A method defined inside a class with the decorator @staticmethod
can be executed without creating a class object. However, the same can be done even if the decorator was not used:
className.MethodName()
So, why should we bother about using @staticmethod?
If you make an instance of a class that has a staticmethod that takes arguments with no decorator it will expect self as the first argument.
class SomeClass:
def somemethod(something):
print(something)
it_fails = SomeClass()
it_fails.somemethod('fail')
Error:
TypeError: somemethod() takes 1 positional argument but 2 were given
Using the
@staticmethod
stops it expecting self as the first argument
class SomeClass:
@staticmethod
def somemethod(something):
print(something)
its_ok = SomeClass()
its_ok.somemethod('Does not fail')
Output:
Does not fail
To expand on what Yoriz said, there are three basic use cases for class methods in Python:
- You need access to the instance: use a method with no decorator, and the instance will be automatically provided as the first parameter. This is your standard run of the mill method.
- You need access to the class: use a method with the classmethod decorator, and the class will be automatically provided s the first parameter. I often use these for alternate constructors.
- You don't need access to the instance or the method: use a method with the staticmethod decorator. This is for code you want to keep associated with the code, but isn't necessarily focused on a particular instance or the class itself.
@
Yoriz
@
ichabod801
Thanks to both of you for your generous explanations of the concept in question. The example given has helped me understand it better.
Regards,
Dev.