Python函数组合

时间:2010-02-17 09:11:51

标签: python function-composition

我尝试用很好的语法实现函数组合,这就是我所拥有的:

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

哪里出错?

1 个答案:

答案 0 :(得分:9)

append进行就地添加,正如Ignacio Vazquez-Abrams所说(嗯,暗示) - 所以,虽然你可以通过向你的函数添加return来修复它,但它会有改变它所通过的论证的副作用:

@composable
def f4(a):
    a.append(0)
    return a

最好使用以下更简洁的代码,这些代码也会创建并返回一个新对象:

@composable
def f4(a):
  return a + [0]
相关问题