Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a class method using the correct decorator.
Python
class MyClass: [1] def greet(cls): return "Hello from class!"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @staticmethod instead of @classmethod
Forgetting the decorator entirely
Using @property which is for attributes
✗ Incorrect
The @classmethod decorator is used to define a method that receives the class itself as the first argument.
2fill in blank
mediumComplete the class method to return the class name using the cls parameter.
Python
class Animal: @classmethod def get_class_name([1]): return [1].__name__
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self' which is for instance methods
Using reserved words like 'class'
Using 'this' which is not Python syntax
✗ Incorrect
Class methods receive the class as the first parameter, usually named 'cls'.
3fill in blank
hardFix the error in the class method to correctly create an instance using cls.
Python
class Person: def __init__(self, name): self.name = name @classmethod def create(cls, name): return [1](name)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Person' directly which breaks inheritance
Using 'self' which is not defined in class methods
Using 'name' which is a string, not a class
✗ Incorrect
Inside a class method, use 'cls' to create new instances so it works correctly with subclasses.
4fill in blank
hardFill both blanks to define a class method that counts how many instances were created.
Python
class Counter: count = 0 def __init__(self): Counter.count += 1 @[1] def get_count([2]): return [2].count
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @staticmethod which does not receive class or instance
Using 'self' in a class method
Forgetting the decorator
✗ Incorrect
The method must be decorated with @classmethod and receive 'cls' to access class variables.
5fill in blank
hardFill all three blanks to create a class method that returns a dictionary with uppercase class name as key and count as value.
Python
class Tracker: count = 0 def __init__(self): Tracker.count += 1 @[1] def summary([2]): return { [3]: [2].count }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self' instead of 'cls' in class method
Using @staticmethod instead of @classmethod
Using a string literal instead of cls.__name__.upper()
✗ Incorrect
Use @classmethod and 'cls' parameter; the key is the uppercase class name accessed by cls.__name__.upper().