python 语法糖太多_几个 Python 语法糖的实现

1. compose

实现compose函数,满足如下操作:

f = lambda x: x**2 + 1

g = lambda x: 2*x - 1

h = lambda x: -2 * x**3 + 3

fgh = compose(f, g, h)

# equivalent to `f(g(h(n)))`

print fgh(5) # 245026

我们可以让compose返回一个函数,这个函数倒序遍历compose中的参数,并对输入参数调用该参数。

def compose(*args):

def retFunc(x):

i = len(args) - 1

while i >= 0:

func = args[i]

assert(func.__call__)

x = func(x)

i -= 1

return x

return retFunc

2. composable

实现composable函数,满足如下操作:

@composable

def add2(x):

return x + 2

@composable

def mul3(x):

return x * 3

@composable

def pow2(x):

return x ** 2

fn = add2 * mul3 * pow2

# equivalent to `add2(mul3(pow2(n)))`

print fn(5) # 77

composable函数接受一个函数,返回一个封装后的东西让其可以通过*来复合。那我们就创建一个类来封装这些东西好了。

class Composable(object):

def __init__(self, *args):

object.__init__(self)

for f in args:

assert(f.__call__)

self.func = args

def __call__(self, x):

i = len(self.func) - 1

while i >= 0:

func = self.func[i]

assert(func.__call__)

x = func(x)

i -= 1

return x

def __mul__(self, rv):

assert(isinstance(rv, Composable))

return Composable(*(self.func + rv.func))

composable = Composable

3.infix

实现infix,满足:

@infix

def plus(a, b):

return a + b

print 1 /plus/ 2

# equivalent to `plus(1, 2)`

print 1 /of/ int

# equivalent to `isinstance(1, int)`

print 1 /to/ 10

# equivalent to `range(1, 11)`

我们可以看到,infix函数接受一个函数,并把这个函数变成中缀。of可以看做isinstance的中缀,to可以看做range的中缀(需要微调)。

我们先把后两个定义出来:

of = infix(isinstance)

to = infix(lambda x, y: range(x, y + 1))

然后实现infix:

class Infix(object):

def __init__(self, f):

object.__init__(self)

assert(f.__call__)

self.func = f

self.set = False

def __rdiv__(self, i):

assert(not self.set)

r = Infix(self.func)

r.set = True

r.left = i

return r

def __div__(self, t):

assert(self.set)

r = self.func(self.left, t)

self.set = False

return r

def __call__(self, *args, **kwargs):

return self.f(*args, **kwargs)

infix = Infix

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值