Class methods let you work with the class itself, not just one object. Using cls helps you change or use class-wide information easily.
Class methods and cls usage in Python
class ClassName: @classmethod def method_name(cls, parameters): # code using cls to access class variables or methods
The @classmethod decorator marks the method as a class method.
cls is like self, but it points to the class, not an object.
class Dog: species = 'Canis familiaris' @classmethod def get_species(cls): return cls.species
class Dog: count = 0 def __init__(self, name): self.name = name Dog.count += 1 @classmethod def how_many(cls): return cls.count
class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_birth_year(cls, name, birth_year): current_year = 2024 age = current_year - birth_year return cls(name, age)
This program shows how class methods can read and change a class variable shared by all objects. Changing wheels affects all cars.
class Car: wheels = 4 def __init__(self, brand): self.brand = brand @classmethod def number_of_wheels(cls): return cls.wheels @classmethod def change_wheels(cls, new_count): cls.wheels = new_count # Check wheels before change print(Car.number_of_wheels()) # Change wheels for all cars Car.change_wheels(6) # Check wheels after change print(Car.number_of_wheels()) # Create a car and check wheels my_car = Car('Toyota') print(my_car.number_of_wheels())
Class methods can be called on the class itself or on an instance.
Using cls inside class methods helps keep code flexible if the class name changes.
Class methods cannot access instance variables directly because they don't get self.
Class methods work with the class, not individual objects.
cls is used inside class methods to refer to the class.
Use class methods to manage or change class-wide data or create alternative constructors.
Practice
cls keyword represent inside a class method in Python?Solution
Step 1: Understand the role of
Inside a class method,clsin class methodsclsrefers to the class, not an instance.Step 2: Differentiate
clsfromselfselfrefers to an instance, whileclsrefers to the class itself.Final Answer:
The class itself -> Option BQuick Check:
cls= class [OK]
- Confusing cls with self
- Thinking cls is a local variable
- Assuming cls is an instance
Solution
Step 1: Identify the decorator for class methods
Class methods require the@classmethoddecorator above the method.Step 2: Check the method parameter
Class methods takeclsas the first parameter, notself.Final Answer:
@classmethod\ndef method(cls): -> Option DQuick Check:
Class method = @classmethod + cls parameter [OK]
- Forgetting the @classmethod decorator
- Using self instead of cls
- Defining without any decorator
class Dog:
species = 'Canine'
@classmethod
def get_species(cls):
return cls.species
print(Dog.get_species())Solution
Step 1: Understand class attribute access via cls
The class methodget_speciesreturnscls.species, which is 'Canine'.Step 2: Check the print statement output
CallingDog.get_species()returns 'Canine', which is printed.Final Answer:
'Canine' -> Option AQuick Check:
cls.species = 'Canine' [OK]
- Expecting instance name instead of class attribute
- Confusing output with class name string
- Thinking it returns None
class Cat:
count = 0
@classmethod
def increment(cls):
count += 1
Cat.increment()Solution
Step 1: Identify variable usage inside class method
The method tries to incrementcountwithoutcls., causing an error.Step 2: Correct usage of class attribute inside class method
It should becls.count += 1to modify the class attribute.Final Answer:
Using count without cls prefix inside method -> Option AQuick Check:
Use cls.count to access class variable [OK]
- Forgetting cls. before class variable
- Using self in class method
- Missing decorator
Example:
Person.from_string('John-25') creates Person('John', 25).Which code snippet correctly implements this?
Solution
Step 1: Recognize the use of class method as alternative constructor
The method should be decorated with@classmethodand takeclsas first parameter.Step 2: Parse string and return new instance
Split the string, convert age to int, and returncls(name, int(age))to create a new object.Final Answer:
@classmethod with cls parameter returning cls instance -> Option CQuick Check:
Alternative constructor = @classmethod + cls + return cls(...) [OK]
- Using @staticmethod instead of @classmethod
- Missing cls parameter or using self
- Not returning cls instance
Ready to prove it?
Pass the test and this pattern moves unknown
