Python uses classmethod to define a class method

Document 对象参考手册Python3 Examples

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

The following is an example of usingclassmethodto define 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 namedMyClass.
  2. class_variable = "This is a class variable"defines a class variable shared by all instances.
  3. @classmethodis a decorator used to turn the following methodclass_methodinto a class method.
  4. def class_method(cls):defines a class method,clsis 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())calls the class method through the class itself.
  7. obj = MyClass()Creates anMyClassinstance of.
  8. print(obj.class_method())calls the class method through an 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 itself or through an instance, the result is the same because the class method is bound to the class.

Document 对象参考手册Python3 Examples

Other extensions