Bird
0
0

Identify the issue in this code snippet:

medium📝 Debug Q6 of 15
Python - Magic Methods and Operator Overloading
Identify the issue in this code snippet:
class Animal:
    def __init__(self, species):
        self.species = species
    def __repr__(self):
        return species

pet = Animal('Dog')
print(pet)
A__init__ method is missing the self parameter
BThe __repr__ method should return self.species, not species
CThe class name should be lowercase
Dprint(pet) cannot be used with __repr__ method
Step-by-Step Solution
Solution:
  1. Step 1: Check __repr__ method

    The method tries to return 'species' which is undefined in its scope.
  2. Step 2: Use instance attribute

    It should return self.species to access the instance variable.
  3. Final Answer:

    The __repr__ method should return self.species, not species -> Option B
  4. Quick Check:

    Use self to access instance variables [OK]
Quick Trick: Always use self to access instance attributes [OK]
Common Mistakes:
  • Returning variable without self prefix inside methods
  • Misunderstanding __repr__ purpose
  • Ignoring scope of variables inside methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes