Recall & Review
beginner
What is a class method in Python?A class method is a method that is bound to the class and not the instance. It receives the class itself as the first argument, usually named <code>cls</code>, allowing it to access or modify class state.Click to reveal answer
beginner
How do you define a class method in Python?You define a class method by decorating a method with <code>@classmethod</code> and including <code>cls</code> as the first parameter in the method definition.Click to reveal answer
intermediate
Why use <code>cls</code> instead of <code>self</code> in a class method?<code>cls</code> refers to the class itself, allowing the method to access or modify class variables and create new instances. <code>self</code> refers to an instance of the class, used in instance methods.Click to reveal answer
intermediate
Can a class method create an instance of the class? How?Yes, a class method can create an instance by calling <code>cls()</code> with appropriate arguments. This is useful for alternative constructors.Click to reveal answer
beginner
Example: What does this code output?<br><pre>class Dog:
species = 'Canis'
@classmethod
def get_species(cls):
return cls.species
print(Dog.get_species())</pre>The output is <code>Canis</code>. The class method <code>get_species</code> accesses the class variable <code>species</code> using <code>cls.species</code>.Click to reveal answer
What is the first argument of a class method in Python?
✗ Incorrect
Class methods receive the class itself as the first argument, which is conventionally named
cls.Which decorator is used to define a class method?
✗ Incorrect
The
@classmethod decorator marks a method as a class method.What can a class method access even without an instance?
✗ Incorrect
Class methods can access class variables via
cls, even without an instance.Which of these is a typical use of a class method?
✗ Incorrect
Class methods are often used as alternative constructors to create instances in different ways.
What will this code print?<br>
class Cat:
count = 0
@classmethod
def increment(cls):
cls.count += 1
Cat.increment()
print(Cat.count)✗ Incorrect
The class method increments the class variable
count by 1, so the output is 1.Explain what a class method is and how the
cls parameter is used.Think about how class methods relate to the class itself, not instances.
You got /4 concepts.
Describe a situation where using a class method is better than an instance method.
Consider when you want to create or manage objects without needing an existing object.
You got /3 concepts.