Utilizing Class Methods
A Class Method
is a method that takes the class itself as the first argument when executed.
It is commonly used to access or modify class variables and perform operations that affect the class rather than instances.
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.
You can call class methods using the class name or through an instance of the class.
# 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 primarily used to access or update class-level data shared among all instances.
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 modify instance variables. They should be used only to work with class variables or perform operations related to the class as a whole.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.