题
我试图实现具有很好的语法功能组成,这里是我有:
from functools import partial
class _compfunc(partial):
def __lshift__(self, y):
f = lambda *args, **kwargs: self.func(y(*args, **kwargs))
return _compfunc(f)
def __rshift__(self, y):
f = lambda *args, **kwargs: y(self.func(*args, **kwargs))
return _compfunc(f)
def composable(f):
return _compfunc(f)
@composable
def f1(x):
return x * 2
@composable
def f2(x):
return x + 3
@composable
def f3(x):
return (-1) * x
print f1(2) #4
print f2(2) #5
print (f1 << f2 << f1)(2) #14
print (f3 >> f2)(2) #1
print (f2 >> f3)(2) #-5
它正常工作与整数,但未能在列表/元组:
@composable
def f4(a):
a.append(0)
print f4([1, 2]) #None
其中是一个错误?
解决方案
append
确实就地此外,伊格纳西奥巴斯克斯 - 艾布拉姆斯说(当然,暗示) - 所以,当你能解决这个问题只需添加一个return
你的功能,就必须改变参数的副作用它传递,也:
@composable
def f4(a):
a.append(0)
return a
这将是最好使用下面的更简洁的代码还创建并返回一个新的对象:
@composable
def f4(a):
return a + [0]
不隶属于 StackOverflow