Bird
0
0

Identify the problem in this code snippet:

medium📝 Debug Q7 of 15
Python - Magic Methods and Operator Overloading
Identify the problem in this code snippet:
class Sample:
    def __init__(self, value):
        self.value = value
    def __len__(self):
        print(self.value)
s = Sample(10)
print(len(s))
Aprint(len(s)) should be print(s.__len__())
BMissing return statement in __init__
Clen() cannot be used on custom objects
D__len__ should return an integer, not print
Step-by-Step Solution
Solution:
  1. Step 1: Understand __len__ method requirements

    __len__ must return an integer representing length, not print anything.
  2. Step 2: Analyze the code behavior

    Here __len__ prints value but returns None, so print(len(s)) outputs None and prints 10 separately.
  3. Final Answer:

    __len__ should return an integer, not print -> Option D
  4. Quick Check:

    __len__ must return int, not print [OK]
Quick Trick: __len__ must return length as int, not print it [OK]
Common Mistakes:
  • Using print instead of return in __len__
  • Thinking len() can't be used on objects
  • Confusing print(len(s)) with print(s.__len__())

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes