Bird
Raised Fist0

Identify the error in this code:

medium📝 Debug Q6 of Q15
Python - Class Methods and Static Methods
Identify the error in this code:
class Person:
    name = "Unknown"

    @classmethod
    def set_name(cls, name):
        self.name = name

Person.set_name("Alice")
print(Person.name)
AUsing self instead of cls inside class method
BMissing @staticmethod decorator
CCalling class method on instance instead of class
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check parameter usage in class method

    The method uses self.name, but class methods should use cls to access class variables.
  2. Step 2: Understand effect of error

    Using self causes a NameError because self is not defined in class method scope.
  3. Final Answer:

    Using self instead of cls inside class method -> Option A
  4. Quick Check:

    Class methods use cls, not self [OK]
Quick Trick: Use cls, not self, inside class methods [OK]
Common Mistakes:
MISTAKES
  • Confusing self and cls
  • Forgetting to use cls to access class variables
  • Assuming class methods behave like instance methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes