Python classmethod Decorator
Description
classmethodThe function corresponding to the decorator does not need to be instantiated, nor does it need the self parameter, but the first parameter needs to be the cls parameter representing the class itself. It can be used to call class attributes, class methods, instantiate objects, etc.
Syntax
classmethod syntax:
classmethod
Parameters
- None.
Return Value
Returns the class method of the function.
Example
The following example demonstrates how to use classmethod:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class A(object):
bar = 1
def func1(self):
print ('foo')
@classmethod
def func2(cls):
print ('func2')
print (cls.bar)
cls().func1() # Call the foo method
A.func2() # No instantiation needed
The output result is:
func2 1 fooOther Extensions
Python Built-in Functions