Bird
0
0

To make a custom class support both the len() function and element access via indexing (e.g., obj[0]), which magic methods must be implemented?

hard📝 Application Q9 of 15
Python - Magic Methods and Operator Overloading
To make a custom class support both the len() function and element access via indexing (e.g., obj[0]), which magic methods must be implemented?
A__length__ and __index__
B__len__ and __getitem__
C__size__ and __get__
D__count__ and __access__
Step-by-Step Solution
Solution:
  1. Step 1: len() support

    Implement __len__ to return the number of elements.
  2. Step 2: Indexing support

    Implement __getitem__ to allow access via obj[index].
  3. Final Answer:

    __len__ and __getitem__ -> Option B
  4. Quick Check:

    __len__ for length, __getitem__ for indexing [OK]
Quick Trick: Use __len__ for length, __getitem__ for indexing [OK]
Common Mistakes:
  • Using non-existent magic methods like __length__
  • Confusing __index__ with __getitem__
  • Not implementing both methods for full behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes