Skip to content
All apps

Operators are methods

About this app

Which method does a * b call? A flow diagram shows the two stations a.__mul__(b) and b.__rmul__(a) with the exits result, NotImplemented and error. With numbers, strings, lists, fractions in four stages (isinstance, __rmul__, __eq__) and runs with and without __lt__: why 3 * Bruch(1, 2) first fails at the int and then ends up in __rmul__.

Operators are method calls

In Python, a * b is shorthand for the method call a.__mul__(b). If a does not have the method or it returns NotImplemented, Python tries the reflected variant b.__rmul__(a). Only if that fails too is there a TypeError. In the same way + belongs to __add__, < to __lt__ and == to __eq__. Your own classes can define these methods and so work with operators. Without __eq__, == compares identity: two objects that look the same are then considered different.

What the app shows

At the top an expression bar with left operand, operator and right operand. Below it a flow diagram with two stations, a.__op__(b) and b.__rop__(a), and the exits result, NotImplemented and error. Next to it the class card Bruch (fraction) or Lauf (run), on which the called method lights up, and small cards for int, str and list. The results match Python 3.13, including the error messages.

Try it yourself

Combine numbers, strings, lists, fractions and runs with +, *, < and ==. The fraction class comes in four stages: only __mul__, then with an isinstance check, then with __rmul__ and finally with __eq__. Follow why 3 * Bruch(1, 2) first fails at int and from stage 3 on ends up in __rmul__, and switch __lt__ on and off for runs.

Frequently asked questions

What happens in Python for a * b?
Python first calls a.__mul__(b). If that method returns NotImplemented or does not exist, Python calls b.__rmul__(a). If that fails as well, Python raises TypeError: unsupported operand type(s).
What is __rmul__ for?
__rmul__ is the reflected multiplication. It is called when your object is on the right of the operator and the left operand cannot handle it. That is how 3 * Fraction(1, 2) works even though int knows nothing about fractions.
What does NotImplemented mean in Python?
NotImplemented is a special return value with which an operator method says: I cannot handle this partner. Python then tries the reflected method of the other operand. An exception raised inside the method, on the other hand, stops everything immediately.
What can I test in the app Operators are methods?
Expressions with +, *, < and == built from numbers, strings, lists, fractions and runs. A flow diagram shows which method is called and which exit applies, and the fraction class can be extended in four stages.

Subject: Computer science

More from Computer science

A VisuApp by heyprof: interactive, free in your browser, no sign-up. What is a VisuApp? · All apps