Python uses classmethod to define a class method
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())
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:
class MyClass:defines a class namedMyClass.class_variable = "This is a class variable"defines a class variable shared by all instances.@classmethodis a decorator used to turn the following methodclass_methodinto a class method.def class_method(cls):defines a class method,clsis the first parameter of the class method, representing the class itself.return f"Class method called. Class variable: {cls.class_variable}"returns a string containing the value of the class variable.print(MyClass.class_method())calls the class method through the class itself.obj = MyClass()Creates anMyClassinstance of.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.
Other extensions
Python3 Examples