Python classmethod Decorator
Description
classmethod The function corresponding to the decorator does not need to be instantiated and does not need a self parameter, but the first parameter needs to be a cls parameter representing its own class, which can be used to call class attributes, class methods, instantiate objects, and so on.
Syntax
classmethod Syntax:
classmethod
Parameters
- none.
Return Value
Returns the class method of a function.
Example
The following examples show the use of classmethod:
#!/usr/bin/python
-- coding: UTF-8 --
class
A
(
object
)
:
bar
=
1
def
func1
(
self
)
:
(
'
foo
'
)
@
classmethod
def
func2
(
cls
)
:
(
'
func2
'
)
(
cls
.
bar
)
cls
(
)
.
func1
(
)
Call the foo method
A
.
func2
(
)
No instantiation needed
The output is:
func2
1
foo
Python built-in function