Suppose I have s class, that has members op, left, right (this is related question to How to assign an operation like sum or substitute, etc., to a variable ). So, in op I store an operator, for example – operator.add, operator.radd, etc. But I want to store operator.rfloordiv and there’s no such member in this class? :\ But I can overload __rfloordiv__, so it does exist at all.
The idea is to apply op to left and right when needed.
My approach is as follows: store some special string in my op and then, before applying op, to check if op is string. If so, write an ugly if-else statement, to check for all – rfloordiv, rmod, rtruediv. If not – just apply op with both parameters. But this is damn ugly..
Is there a better way to achieve this?
I know that this could be done with lambda function, but if I do it like this, is there any way to see what is this lambda function (for the moment, when I need to see what is op, I check it in an if statement like this: if self.op is operator.radd: .., but what if op is lambda function ? )
Most magic operator methods come in two flavours: the plain variant and the variant prefixed with
r(example__add__()and__radd()__). If you try to add the objectsaof typeAandbof typeB, Python first callsA.__add__(a, b). If this returns the special valueNotImplemented,B.__radd__(b, a)is called.Both those magic methods corresond to
operator.addin theoperatormodule. Similarly, the magic methods__floordiv__()and__rfloordiv__()correspond tooperator.floordiv.