请逐步解释 Python Infix Hack 中的 Infix class 实例化和运算符重载的工作原理
Please give a step-by-step explanation of how Infix class from the Python Infix Hack instantination and operators overloading work
This article 展示了在 python.
中使用函数式编程创建自定义中缀运算符的方法
这里是文中描述的中缀class的简化版本:
class Infix:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
return self.function(other)
及其用法的一些示例:
# simple multiplication
x=Infix(lambda x,y: x*y)
print 2 |x| 4
# => 8
# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
print [1,2,3] |isa| []
# => True
我想我了解运算符的右手版本以及双下划线方法的工作原理,但我无法完全理解这个 hack 的工作原理。
2 |x| 4
呼叫 x.__ror__(2).__or__(4)
。现在 x.__ror__(2)
returns Infix(lambda arg, self=self, other=other: self.function(other, arg))
,在这种情况下 self.function
是 lambda x,y: x*y
而 other
是 2
。所以我们得到:Infix(lambda arg, self=x, other=2: other * arg)
。在此我们调用 .__or__(4)
,其中 returns self.function(other)
其中 other
是 4
。所以:
(lambda arg, self=x, other=2: other * arg)(4)
===
arg = 4
self = x
other = 2
other * arg
===
4 * 2
===
8
所以我们得到 8。
This article 展示了在 python.
中使用函数式编程创建自定义中缀运算符的方法这里是文中描述的中缀class的简化版本:
class Infix:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
return self.function(other)
及其用法的一些示例:
# simple multiplication
x=Infix(lambda x,y: x*y)
print 2 |x| 4
# => 8
# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
print [1,2,3] |isa| []
# => True
我想我了解运算符的右手版本以及双下划线方法的工作原理,但我无法完全理解这个 hack 的工作原理。
2 |x| 4
呼叫 x.__ror__(2).__or__(4)
。现在 x.__ror__(2)
returns Infix(lambda arg, self=self, other=other: self.function(other, arg))
,在这种情况下 self.function
是 lambda x,y: x*y
而 other
是 2
。所以我们得到:Infix(lambda arg, self=x, other=2: other * arg)
。在此我们调用 .__or__(4)
,其中 returns self.function(other)
其中 other
是 4
。所以:
(lambda arg, self=x, other=2: other * arg)(4)
===
arg = 4
self = x
other = 2
other * arg
===
4 * 2
===
8
所以我们得到 8。