开发者

Module `operator` in python has no `rfloordiv`?

开发者 https://www.devze.com 2023-02-28 19:32 出处:网络
Suppose I have s class, that has members op, left, right (this is related question to How开发者_Python百科 to assign an operation like sum or substitute, etc., to a variable ). So, in op I store an op

Suppose I have s class, that has members op, left, right (this is related question to How开发者_Python百科 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 objects a of type A and b of type B, Python first calls A.__add__(a, b). If this returns the special value NotImplemented, B.__radd__(b, a) is called.

Both those magic methods corresond to operator.add in the operator module. Similarly, the magic methods __floordiv__() and __rfloordiv__() correspond to operator.floordiv.

0

精彩评论

暂无评论...
验证码 换一张
取 消