Skip to main content
Practice

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).

Example of Using Class Methods
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.

Calling a Class Method
# 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.

Modifying Class Variables Using Class Methods
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.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.