Utilizing Class Methods
Class Method
is a method that takes the class itself as the first argument when executed.
It's used to access class variables or perform operations at the class level.
Class methods are defined with the @classmethod
decorator (a function that wraps another function, extending the wrapped function's capabilities).
Example of Using Class Methods
Class methods receive the class itself as the first parameter (cls)
rather than an instance (self)
.
class MyClass: # Class variable class_variable = "Common value" # Define class method @classmethod def class_method(cls): return f"Class method call: {cls.class_variable}"
In the code above, class_method
is a class method that accesses the class variable through the cls
parameter.
Class methods can be called using either the class name or an instance.
# Call with class name print(MyClass.class_method()) # Output: Class method call: Common value # Call through an instance instance = MyClass() print(instance.class_method()) # Output: Class method call: Common value
Class methods are mainly used to read or modify class variables.
class Counter: count = 0 # Class variable @classmethod def increment(cls): cls.count += 1 return cls.count # Call class method print(Counter.increment()) # Output: 1 print(Counter.increment()) # Output: 2
Class methods cannot change the state of an instance (instance variables) and should be used to manipulate class variables or the class itself.
Class methods can be called without creating an instance of a class.
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result