Dunder Methods and Composition
Scenario: Objects need readable logs and equality, while a deployment should contain services rather than become a service.
New words, in plain English
- Dunder method - a special double-underscore hook used by Python syntax
- Composition - building an object from other objects - a has-a relationship
- Equality - whether values should count as equivalent
__str__ controls friendly text, __repr__ debugging text, __eq__ equality, and __len__ length. Return NotImplemented for unsupported comparison types. Prefer composition for has-a relationships.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
class Service:
def __init__(self, name): self.name = name
def __str__(self): return self.name
def __eq__(self, other):
if not isinstance(other, Service): return NotImplemented
return self.name == other.name
Tip: Implement special methods only when their normal Python meaning fits naturally.
Goal: Practice this idea in the py-oop-inheritance challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.