假设我有 s 类,它有成员 op
、left
、right
(这是与 如何将求和或替换等操作分配给变量)。因此,在 op
中,我存储一个运算符,例如 - operator.add
、operator.radd
等。但我想存储 operator.rfloordiv
并且这个类中没有这样的成员? :\ 但我可以重载__rfloordiv__
,所以它确实存在。
这个想法是在需要时将 op
应用于 left
和 right
。
我的方法如下:在我的 op
中存储一些特殊字符串,然后在应用 op
之前检查 op
是否是字符串。如果是这样,请编写一个丑陋的 if-else
语句,以检查所有 - rfloordiv
、rmod
、rtruediv
。如果不是 - 只需将 op
与两个参数一起应用。但这太丑陋了..
有更好的方法来实现这一目标吗?
我知道这可以通过 lambda 函数来完成,但是如果我这样做,有什么方法可以查看这个 lambda 函数是什么(目前,当我需要查看什么是 op
,我在 if
语句中检查它,如下所示: if self.op is operator.radd: ..
,但是如果 op
是 lambda
函数怎么办?)
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 ? )
发布评论
评论(1)
大多数魔术运算符方法有两种类型:普通变体和以
r
为前缀的变体(例如__add__()
和__radd()__
)。如果您尝试添加A
类型的对象a
和B
类型的b
,Python 首先调用A.__add__(a, b)
。如果返回特殊值NotImplemented
,则调用B.__radd__(b, a)
。这两个魔术方法都与
operator
模块中的operator.add
相对应。同样,魔术方法__floordiv__()
和__rfloordiv__()
对应于operator.floordiv
。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 objectsa
of typeA
andb
of 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.add
in theoperator
module. Similarly, the magic methods__floordiv__()
and__rfloordiv__()
correspond tooperator.floordiv
.