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

Python Defining a Class Method with classmethod

Python Defining a Class Method with classmethod

Document Object Reference Manual Python3 Examples

In Python,classmethod is a decorator used to define class methods. A class method is bound to the class rather than to an instance and can be called through the class itself or through an instance. The first parameter of a class method is usually cls, which represents the class itself.

Below is an example using classmethod Example of defining a class method:

Example

class

MyClass:

    class_variable

=

"This is a class variable"

   

@

classmethod

   

def

class_method

(

cls

)

:

       

return

f

"Class method called. Class variable: {cls.class_variable}"

Call the class method through the class

print

(

MyClass.

class_method

(

)

)

Call the class method through an instance

obj

=

MyClass

(

)

print

(

obj.

class_method

(

)

)

Code analysis:

  1. class MyClass: defines a class named MyClass .
  2. class_variable = "This is a class variable" defines a class variable shared by all instances.
  3. @classmethod is a decorator that marks the method below class_method as a class method.
  4. def class_method(cls): defines a class method;cls is the first parameter of the class method, representing the class itself.
  5. return f"Class method called. Class variable: {cls.class_variable}" returns a string containing the value of the class variable.
  6. print(MyClass.class_method()) Call the class method through the class itself.
  7. obj = MyClass() Created a MyClass instance of
  8. print(obj.class_method()) Call the class method through the instance.

Output result:

Class method called. Class variable: This is a class variable
Class method called. Class variable: This is a class variable

Whether the class method is called through the class or through an instance, the result is the same, because a class method is bound to the class.

Document Object Reference Manual Python3 Examples