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
@classmethod
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]):
pass
classmethod() example
# classmethod() example
class Dog:
name = 'Mike'
def get_name(self):
print(self.name)
# create class method
Dog.get_name = classmethod(Dog.get_name)
# call class method
Dog.get_name()
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.
Mike
classmethod() syntax
The syntax of the classmethod function is:
classmethod(function)
classmethod() arguments
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.
related functions
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.