Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python classmethod Decorator

Python classmethod Decorator

Python built-in function Python built-in function


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

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

)

:

print

(

'

foo

'

)

@

classmethod

def

func2

(

cls

)

:

print

(

'

func2

'

)

print

(

cls

.

bar

)

cls

(

)

.

func1

(

)

Call the foo method

A

.

func2

(

)

No instantiation needed

The output is:

func2
1
foo

Python built-in function Python built-in function