staticmethod() vs. decorators
The staticmethod() function returns a static method for a given function. An alternative to using the staticmethod() function is to use decorators to create static methods, this is considered a more pythonic way. The syntax of the staticmethod decorator is:
@staticmethod
def function()
What are static methods?
Static methods are not bound to a class.
They don't require the class as first argument, like class methods do.
A static method can't access or modify the class state, while a class method can do that.
The static methods use the parameters passed to them and not class attributes.
staticmethod() example
To create a static method, use the staticmethod() function and pass the function as argument.
# staticmethod() example
# define class
class Words:
def concatenate(word1, word2):
return word1 + ' ' + word2
# create static method
Words.add = staticmethod(Words.add)
# call static method
print(Words.concatenate('hello', 'world'))
The static method is created and called. The words are concatenated and printed.
hello world
staticmethod() syntax
The syntax of the staticmethod function is:
staticmethod(function)
staticmethod() arguments
The staticmethod() function takes exactly one argument, the functions to be converted to a static method.
staticmethod() return values
The staticmethod() function returns the static method of the function passed as the argument.
related functions
The related function of the staticmethod() is the classmethod() function. It returns the class method of a function, instead of a static method.