A couple more along the same lines:
- Metaclasses and type. (This is admittedly dark magic, but useful in library code, less so in application code)
- Magic methods! Everyone knows about __init__, but you can override all sorts of behaviors (see: https://docs.python.org/3/reference/datamodel.html)
My favorite example (I have a lot of favorite examples :)) is __call__, which emulates function calling and is the equivalent of C++'s operator().
Why is it my favorite? Because as the old adage goes, "a class is a poor man's closure, a closure is a poor man's class":
class C:
def __init__(self, x):
self.x = x
def __call__(self, y):
return self.x + y
>>> a = C(2)
>>> a(3)
5I didn't have to use Metaclasses, either, though I have read about them, especially in Fluent Python. But I guess I belong to the 99% who haven't had to worry about them, yet :P
What is the benefit compared to having a method named "add" that also explains the behavior?
It may also give you a "clearer" (in quotes because subjective) presentation for something you're trying to do.
processor = SomeProcessor.load("path/to/config")
# with __call__
processed_inputs = processor(inputs)
# less awkward than
processes_inputs = processor.process(inputs)
The only benefit is to the human, same as @property or even @dataclass.