classmethod() vs decorator
The classmethod() function in Python returns a class method of the given function.
An alternative and more pythonic way to define a class method is the decorator @classmethod.
# define classmethod using @classmethod decorator
def func(class[, args])
what is a class method?
A class method is a method that is bound to a class. It doesn't require the initiation of a class similar to the static method.
The class method is attached to the class and the first argument is always the class itself.
# class method
def myClassMethod(class[, args]):
# classmethod() example
name = 'Mike'
# create class method
Dog.get_name = classmethod(Dog.get_name)
# call class method
In this example, a class named Dog is defined. The name attribute is set to 'Mike'. Then a get_name() method is defined, it will print the name attribute to the screen.
Next, the class method is created using the classmethod() function. And finally the class method is called and the result is printed.
The syntax of the classmethod function is:
The classmethod() function expects exactly one argument, the function to be converted into a class method.
If less or more than one argument is given, a TypeError exception is raised.
classmethod() return values
The classmethod() function returns a class method for the given function.
The related function of the classmethod() function is the staticmethod() function. It creates, like the name suggests, a static method instead of a class method.