class infix(object):
"""
Clever hack (slightly modified) for defining infix operators.
Via http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
Intended for use as a decorator.
>>> @infix
... def removing(str, chars):
... for char in chars:
... str = str.replace(char, '')
... return str
...
>>> print 'Hello, world!' |removing| 'eo'
Hll, wrld!
"""
def __init__(self, function):
self.function = function
def __ror__(self, other):
return infix(lambda x: self.function(other, x))
def __or__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
@infix
def λ(str1, str2):
return eval('lambda '+str1+':'+str2)
print(('x,y' |λ| 'x + y')(5, 6))
上述infix
是一个用类实现的装饰器,它在函数左右进行了两次运算符重载,一次是左|
,这时函数是做为a|b
中的b
,在重载后,变量|函数
的结果是lambda x: 函数(变量, x)
,用数学语言解释即为
f:x×y→zf :x\times y\rightarrow zf:x×y→z
z=f(x,y)z=f(x,y)z=f(x,y)
定义运算符AAA,则x0Af=f(x0,y)=f1(y)x_0 A f = f(x_0,y) =f_1(y)x0Af=f(x0,y)=f1(y).
第二次重载__or__
右|
,这时函数是做为a|b
中的a
,函数|变量
的结果是函数(变量)
,用数学语言解释即为
f1:y→zf_1 : y\rightarrow zf1:y→z
z=f1(y)z=f_1(y)z=f1(y)
定义运算符BBB,则f1By0=f1(y0)f_1 B y_0 = f_1(y_0)f1By0=f1(y0).
则变量1|函数|变量2
的结果为函数(变量1,变量2)
我们通过这个装饰器,把函数λ
装饰为|λ|
,实现类似于Javascript
中=>
运算符的作用.
函数λ
的实现是使用Python3内置的eval
函数,左右两个字符串str1
和str2
通过eval('lambda '+str1+':'+str2)
生成一个匿名函数并返回.