Mysterious symbols
A reader asked a great question. Great because it's a little complex.
Look at this class:
- class Polynomial:
- def __init__(self, *coeffs):
- self.coeffs = coeffs
- def __repr__(self):
- return 'Polynomial(*{!r})'.format(self.coeffs)
- def __add__(self, other):
- return Polynomial(*(x + y for x, y in zip(self.coeffs, other.coeffs)))
- def __len__(self):
- return len(self.coeffs)
The question is, basically, "What's going on with this class"?
More precisely:
- What's the meaning of the "*" character? It shows up in like four places.
- In
__repr__
, what's the "!r" mean? - For that matter, why is the method named
__repr__
? Does it have special meaning? - And all these underscores make my head hurt. What are they for?
What's interesting is that if your goal is to understand WHY this code is written this way, you almost have to answer all these questions together. Because the "why" is intertwined.
That's what real code is like.
Right? And toy code is NOT like.
I mean, toycode can demonstrate a single language feature. In isolation.
That's useful, sure.
But:
Realistic applications have a lot going on... moving parts that move together. Nothing in isolation.
That's why it's important to study such code. Make sure you do that, and learn from it.