1

Mathematica では、これを行うことができます

10+10 // Sqrt

20 の平方根を返します。Python をハックして同じことをしようとしています。このような:

10+10 // crazy.sqrt

どのように?crazyクラスの演算子をオーバーライドします。しかし、それは後置です。そして、これによると http://rgruet.free.fr/PQR26/PQR2.6.html#SpecialMethods

任意の演算子をオーバーライドしようとすると、常にself <operator> otherそうであるため、前述のケースでは、int、string、およびその他のトンのようなクラスに対してそれを行う必要があります-悪いです。

これを回避する方法はありますか?other クラスで順序を入れ替えて演算子を再定義したいと思います。(明確化のために編集: 次のようother にクラスに引数として渡されますself: self.__ operator __(...,other))

4

2 に答える 2

1

多分

class WeirdMath:
    def __init__(self,v):
        self.val = v
    def __floordiv__(self,other): #this tells us to apply whatever function to our value
        return other(self.val)

import math
print WeirdMath(10+10) // math.sqrt
print WeirdMath(["a","b","c"]) // " .. ".join

あなたのニーズを満たすかもしれないものは禁じられた果物です ( $ easy_install forbiddenfruit)

from forbiddenfruit import curse
def apply(self,method):
    return method(self)

curse(object,"apply",apply)
def cubed(n):
   return n**3
(10 + 10).apply(math.sqrt).apply(cubed)
"a big yellow house".apply(str.split).apply(" != ".join)
于 2014-07-25T21:57:44.293 に答える