0
0
Pythonprogramming~5 mins

Class methods and cls usage in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aself
Bcls
Cclass
Dthis
Which decorator is used to define a class method?
A@classmethod
B@staticmethod
C@instance
D@property
What can a class method access even without an instance?
AInstance variables
BGlobal variables
CClass variables
DLocal variables
Which of these is a typical use of a class method?
ATo create alternative constructors
BTo modify instance attributes
CTo handle user input
DTo define private methods
What will this code print?<br>
class Cat:
    count = 0

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

Cat.increment()
print(Cat.count)
A0
BError
CNone
D1
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.