Python函数组成
我尝试用漂亮的语法实现函数组合,这就是我得到的:
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
哪里有错误?
I've tried to implement function composition with nice syntax and here is what I've got:
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
It works fine with integers, but fails on lists/tuples:
@composable
def f4(a):
a.append(0)
print f4([1, 2]) #None
Where is a mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
append
进行就地添加,正如 Ignacio Vazquez-Abrams 所说(嗯,隐含的)——因此,虽然您可以通过在函数中添加return
来解决这个问题,它也会产生更改传递的参数的副作用:最好使用以下更简洁的代码,该代码还创建并返回一个新对象:
append
does in-place addition, as Ignacio Vazquez-Abrams said (well, implied) -- so, while you could fix that by just adding areturn
to your function, it would have the side-effect of changing the argument it was passed, too:It would be best to use the following even more concise code which also creates and returns a new object: