9

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

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

哪里有错?

4

1 回答 1

9

append就地添加,正如 Ignacio Vazquez-Abrams 所说(嗯,暗示) - 所以,虽然你可以通过return在函数中添加 a 来解决这个问题,但它也会产生改变它传递的参数的副作用:

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

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

@composable
def f4(a):
  return a + [0]
于 2010-02-17T09:22:02.007 回答