Bird
Raised Fist0
Pythonprogramming~20 mins

Class methods and cls usage in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Class Method Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of class method modifying class variable
What is the output of this code when calling Dog.increment_legs() followed by print(Dog.legs)?
Python
class Dog:
    legs = 4

    @classmethod
    def increment_legs(cls):
        cls.legs += 1

Dog.increment_legs()
print(Dog.legs)
A5
B4
CAttributeError
DTypeError
Attempts:
2 left
💡 Hint
Remember that class methods receive the class as the first argument and can modify class variables.
Predict Output
intermediate
2:00remaining
Output of class method creating instance
What will be printed when running this code?
Python
class Person:
    def __init__(self, name):
        self.name = name

    @classmethod
    def from_full_name(cls, full_name):
        first_name = full_name.split()[0]
        return cls(first_name)

p = Person.from_full_name('Alice Johnson')
print(p.name)
AJohnson
BAlice Johnson
CAlice
DTypeError
Attempts:
2 left
💡 Hint
Look at how the class method processes the full name and what it passes to the constructor.
🧠 Conceptual
advanced
1:30remaining
Understanding cls vs self in methods
Which statement best describes the difference between cls in class methods and self in instance methods?
A<code>cls</code> refers to the instance, while <code>self</code> refers to the class.
B<code>cls</code> refers to the class itself, while <code>self</code> refers to the instance of the class.
C<code>cls</code> and <code>self</code> both refer to the instance but in different contexts.
D<code>cls</code> and <code>self</code> are interchangeable and mean the same.
Attempts:
2 left
💡 Hint
Think about what each method type is designed to work with.
Predict Output
advanced
2:00remaining
Output of class method modifying subclass variable
What will be the output of this code?
Python
class Vehicle:
    wheels = 4

    @classmethod
    def set_wheels(cls, count):
        cls.wheels = count

class Bike(Vehicle):
    wheels = 2

Bike.set_wheels(3)
print(Vehicle.wheels, Bike.wheels)
A3 2
B3 3
C4 2
D4 3
Attempts:
2 left
💡 Hint
Remember that class methods affect the class they are called on, not the parent class.
🔧 Debug
expert
2:30remaining
Identify the error in class method usage
This code is intended to create a new instance with a default name using a class method. What error will it raise when run?
Python
class Cat:
    def __init__(self, name):
        self.name = name

    @classmethod
    def default_cat(cls):
        return cls(name='Whiskers')

c = Cat.default_cat()
print(c.name)
ANo error, prints 'Whiskers'
BTypeError: __init__() got an unexpected keyword argument 'name'
CAttributeError: 'Cat' object has no attribute 'name'
DSyntaxError
Attempts:
2 left
💡 Hint
Check the constructor parameters and how the class method calls it.

Practice

(1/5)
1. What does the cls keyword represent inside a class method in Python?
easy
A. A global variable
B. The class itself
C. A local variable
D. An instance of the class

Solution

  1. Step 1: Understand the role of cls in class methods

    Inside a class method, cls refers to the class, not an instance.
  2. Step 2: Differentiate cls from self

    self refers to an instance, while cls refers to the class itself.
  3. Final Answer:

    The class itself -> Option B
  4. Quick Check:

    cls = class [OK]
Hint: Remember: cls means class, self means instance [OK]
Common Mistakes:
  • Confusing cls with self
  • Thinking cls is a local variable
  • Assuming cls is an instance
2. Which of the following is the correct way to define a class method in Python?
easy
A. def method(cls):
B. def method(self):
C. @staticmethod\ndef method():
D. @classmethod\ndef method(cls):

Solution

  1. Step 1: Identify the decorator for class methods

    Class methods require the @classmethod decorator above the method.
  2. Step 2: Check the method parameter

    Class methods take cls as the first parameter, not self.
  3. Final Answer:

    @classmethod\ndef method(cls): -> Option D
  4. Quick Check:

    Class method = @classmethod + cls parameter [OK]
Hint: Class methods always use @classmethod and cls parameter [OK]
Common Mistakes:
  • Forgetting the @classmethod decorator
  • Using self instead of cls
  • Defining without any decorator
3. What will be the output of the following code?
class Dog:
    species = 'Canine'

    @classmethod
    def get_species(cls):
        return cls.species

print(Dog.get_species())
medium
A. 'Canine'
B. None
C. 'Dog'
D. Error

Solution

  1. Step 1: Understand class attribute access via cls

    The class method get_species returns cls.species, which is 'Canine'.
  2. Step 2: Check the print statement output

    Calling Dog.get_species() returns 'Canine', which is printed.
  3. Final Answer:

    'Canine' -> Option A
  4. Quick Check:

    cls.species = 'Canine' [OK]
Hint: Class methods access class variables via cls [OK]
Common Mistakes:
  • Expecting instance name instead of class attribute
  • Confusing output with class name string
  • Thinking it returns None
4. Find the error in this code snippet:
class Cat:
    count = 0

    @classmethod
    def increment(cls):
        count += 1

Cat.increment()
medium
A. Using count without cls prefix inside method
B. Missing @staticmethod decorator
C. Method should have self parameter
D. Class attribute count is not defined

Solution

  1. Step 1: Identify variable usage inside class method

    The method tries to increment count without cls., causing an error.
  2. Step 2: Correct usage of class attribute inside class method

    It should be cls.count += 1 to modify the class attribute.
  3. Final Answer:

    Using count without cls prefix inside method -> Option A
  4. Quick Check:

    Use cls.count to access class variable [OK]
Hint: Always prefix class vars with cls inside class methods [OK]
Common Mistakes:
  • Forgetting cls. before class variable
  • Using self in class method
  • Missing decorator
5. How can you use a class method to create an alternative constructor that creates an object from a string?
Example: Person.from_string('John-25') creates Person('John', 25).
Which code snippet correctly implements this?
hard
A. class Person: def __init__(self, name, age): self.name = name self.age = age @staticmethod def from_string(data): name, age = data.split('-') return cls(name, int(age))
B. class Person: def __init__(self, name, age): self.name = name self.age = age def from_string(self, data): name, age = self.split('-') return Person(name, int(age))
C. class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_string(cls, data): name, age = data.split('-') return cls(name, int(age))
D. class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_string(self, data): name, age = data.split('-') return cls(name, int(age))

Solution

  1. Step 1: Recognize the use of class method as alternative constructor

    The method should be decorated with @classmethod and take cls as first parameter.
  2. Step 2: Parse string and return new instance

    Split the string, convert age to int, and return cls(name, int(age)) to create a new object.
  3. Final Answer:

    @classmethod with cls parameter returning cls instance -> Option C
  4. Quick Check:

    Alternative constructor = @classmethod + cls + return cls(...) [OK]
Hint: Use @classmethod and cls to build alternative constructors [OK]
Common Mistakes:
  • Using @staticmethod instead of @classmethod
  • Missing cls parameter or using self
  • Not returning cls instance