Arithmetic dunder methods (__add__, __mul__)
22-minute lesson · module-classes-deeper-04
You are previewing this course as a guest
Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.
Arithmetic dunder methods (__add__, __mul__)
22-minute lesson · module-classes-deeper-04
- Explain that operators like + and * call dunder methods such as __add__ and __mul__.
- Define __add__ to make + work on your own class.
- Define __mul__ to make * work on your own class.
- Return a new instance from an arithmetic method rather than mutating self.
Source attribution
Status: adapted
How to Think Like a Computer Scientist: Interactive Edition — source · Classes and Objects - Digging a Little Deeper / Arithmetic Methods
Adaptation notes. Reading rewritten in our voice. Operator overloading is shown on a Fraction class (building on the earlier worked example) with __add__ and __mul__ that return new reduced fractions. Hidden tests check the operator results reduce correctly and leave operands unchanged.
License notes. Original chapter is GNU FDL 1.3 (Brad Miller and David Ranum). No verbatim text from the original is reproduced here.