python 花式中值运算符

class Infix:
    def __init__(self,callable):
        self.func=callable
    # | 运算符 |这个符号在Infix的右边就会调用
    def __or__(self, other):
        print('__or__',other)
        # 这里因为ror的地方带走了一个变量,只需要传一个变量,就可以调用匿名函数
        # 匿名函数在下面,返回一个字符串
        return self.func(other)
    # | 运算符 |这个符号在Infix的左边就会调用
    def __ror__(self, other):
        print('__ror__',other)
        # 这里的匿名函数把other 的变量带走了
        return Infix(lambda var:self.func(other,var))

infix=Infix(lambda a,b :"fanhuizhi")
val='abc' | infix| 'def'
print('result:',val)

注意看防御编程,
infix=Infix(lambda a,b :"fanhuizhi")
val='abc' | infix| 'def'
print('result:',val)

你可能感兴趣的:(python,开发语言)