Lesson 3 of 17
Operator Shortcuts
Operator Shortcuts
Python lets you overload the full set of arithmetic operators. Most can be defined in terms of the operations we already have — no new gradient logic needed.
Negation
-a is just a * -1:
def __neg__(self): return self * -1
Right-hand Operations
Python calls __radd__ when the left operand doesn't know how to add. 3 + a becomes a.__radd__(3):
def __radd__(self, other): return self + other
def __rmul__(self, other): return self * other
Subtraction and Division
Both reduce to existing operations:
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return other + (-self)
def __truediv__(self, other): return self * other**-1
def __rtruediv__(self, other): return other * self**-1
Note other**-1 — this calls Python's built-in ** on the raw number (not Value.__pow__), giving the scalar reciprocal. Then self * scalar uses Value.__mul__ which wraps the scalar automatically.
Your Task
Add all seven shortcut methods to Value.
Python runtime loading...
Loading...
Click "Run" to execute your code.