Challenge - 5 Problems
Class Method Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember that class methods receive the class as the first argument and can modify class variables.
✗ Incorrect
The class method
increment_legs increases the class variable legs by 1. Initially, legs is 4, so after calling the method, it becomes 5.❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Look at how the class method processes the full name and what it passes to the constructor.
✗ Incorrect
The class method splits the full name and takes the first part as the name. It then creates a new instance with that first name. So,
p.name is 'Alice'.🧠 Conceptual
advanced1:30remaining
Understanding cls vs self in methods
Which statement best describes the difference between
cls in class methods and self in instance methods?Attempts:
2 left
💡 Hint
Think about what each method type is designed to work with.
✗ Incorrect
cls is used in class methods to refer to the class itself, allowing access to class variables and other class methods. self is used in instance methods to refer to the specific object instance.❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
Remember that class methods affect the class they are called on, not the parent class.
✗ Incorrect
Calling
Bike.set_wheels(3) changes the wheels variable only for the Bike class. The Vehicle class remains unchanged with 4 wheels.🔧 Debug
expert2: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)
Attempts:
2 left
💡 Hint
Check the constructor parameters and how the class method calls it.
✗ Incorrect
The class method calls the constructor correctly with the keyword argument 'name'. The instance is created with name 'Whiskers', so printing
c.name outputs 'Whiskers'.