Why does `return 1/self` fail on a fraction object, and what hidden method is `*` actually running every time you use it?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
The SimpleFraction class below stores two integers and has one unfinished method. Fill in the body of get_inverse so that it returns a float representing 1 divided by the fraction itself, then build the fraction three over four and assign the object to frac.
Careful: 1/self is not something Python knows how to compute. Only the two integers inside the object are things it can divide.
get_inverse, invert, and the 1/self trap
Write return self.denom/self.num and the tuple swap (self.num, self.denom) = (self.denom, self.num), record that return 1/self raises a TypeError, and trace SimpleFraction(3, 4) printing 1.3333333333333333 then 4 3.
Three things still unsatisfying about the class
List all three: plus and times hand back floats, printing gives <__main__.SimpleFraction object at 0x7f9c...>, and f1 * f2 raises unsupported operand type(s) for *.
Operators as shorthand that runs a method
Record that *, +, <, >, print, len and square-bracket indexing each run a method, list names such as __add__, __mul__, __str__, __float__, __len__, __eq__ and __getitem__, and note only __str__ comes for free.