Dunder Methods — __str__, __eq__, __len__ & Operator Overloading — Concept Check
Questions on Dunder Methods — __str__, __eq__, __len__ & Operator Overloading. Double-underscore methods let your objects speak Python: print() calls __str__, == calls __eq__, len() calls __len__, and + calls __add__ — protocols, not magic.
Questions in this quiz
8 questions on Dunder Methods — __str__, __eq__, __len__ & Operator Overloading — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have a class Money with __eq__ and __hash__ implemented. What happens when you add two Money objects with different currencies?
- AThe __str__ method is called to print the result.
- BA ValueError is raised due to currency mismatch.
- CThe objects are added without error.
- DThe __eq__ method is called to compare currencies.
2.A developer implements __repr__ but not __str__ in a class. What will print(obj) output?
- AAn error, because __str__ is not defined.
- BThe default object memory address.
- CNothing, as __str__ is needed for print.
- DThe __repr__ output, since __str__ defaults to __repr__.
3.Given a Playlist class with __len__, __getitem__, and __contains__, what feature does it not support?
- AIteration over songs.
- BGetting the number of songs.
- CSorting based on song order.
- DChecking if a song is in the playlist.
4.Two Money objects, a and b, have the same amount and currency. What does a == b return?
- AFalse, because __eq__ is not implemented.
- BTrue, because __str__ makes them equal.
- CTrue, because __eq__ compares by value.
- DFalse, because they are different instances.
5.What happens if you try to add a Money object to an integer?
- ATypeError, as __add__ expects a Money object.
- BThe integer is ignored in the addition.
- C__eq__ is called to compare the integer.
- DThe integer is converted to Money and added.
6.A class implements __len__ but not __getitem__. What can it still do?
- AReturn its length using len().
- BSupport indexing with square brackets.
- CBe iterated over using a loop.
- DCheck membership with 'in'.
7.A developer claims __str__ and __repr__ serve the same purpose. What's the key difference?
- A__repr__ is only for error messages.
- BBoth are for printing objects.
- C__str__ is faster than __repr__.
- D__str__ is for users, __repr__ is for developers.
8.In a class with __eq__ but no __hash__, what happens when you use instances in a set?
- ATypeError, because __hash__ is required for set membership.
- BInstances are added without error.
- C__eq__ is used to hash the instances.
- DInstances are compared by memory address.