Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q14 of Q15
Python - Magic Methods and Operator Overloading
Identify the error in this code snippet:
class Person:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return name

p = Person('Alice')
print(p)
AUsing undefined variable 'name' in __str__
BNo error, code runs fine
CIncorrect method name __str__
DMissing return statement in __str__
Step-by-Step Solution
Solution:
  1. Step 1: Check the __str__ method's return value

    The method returns 'name', but 'name' is not defined inside __str__; it should use self.name.
  2. Step 2: Understand variable scope

    Since 'name' is undefined in __str__, this causes a NameError at runtime.
  3. Final Answer:

    Using undefined variable 'name' in __str__ -> Option A
  4. Quick Check:

    Use self.name inside methods [OK]
Quick Trick: Use self.variable to access attributes inside methods [OK]
Common Mistakes:
MISTAKES
  • Forgetting self. before attribute names
  • Thinking __str__ is misspelled
  • Assuming no error occurs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes