Python Defining a Class Method with classmethod
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
(
MyClass.
class_method
(
)
)
Call the class method through an instance
obj
=
MyClass
(
)
(
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 that marks the method belowclass_methodas 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())Call the class method through the class itself.obj = MyClass()Created aMyClassinstance ofprint(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.
Python3 Examples