0
0
Pythonprogramming~10 mins

Class methods and cls usage in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A@classmethod
B@abstractmethod
C@property
D@staticmethod
Attempts:
3 left
💡 Hint
Common Mistakes
Using @staticmethod instead of @classmethod
Forgetting the decorator entirely
Using @property which is for attributes
2fill in blank
medium

Complete 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'
Acls
Bclass
Cself
Dthis
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
3fill in blank
hard

Fix 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'
Aname
Bself
CPerson
Dcls
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
4fill in blank
hard

Fill 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'
Aclassmethod
Bcls
Cstaticmethod
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using @staticmethod which does not receive class or instance
Using 'self' in a class method
Forgetting the decorator
5fill in blank
hard

Fill 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'
Aclassmethod
Bcls
Ccls.__name__.upper()
Dself
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()