这个功能有什么问题?这似乎是一个范围错误(尽管我认为我已经通过将每个可调用对象放在列表中而不是直接使用它来解决这个问题)。错误是达到最大递归深度(调用 comp(inv,dbl,inc) 时)...
注意:问题是:为什么它甚至是递归的,而不是为什么它达到最大深度......
def comp(*funcs):
if len(funcs) in (0,1):
raise ValueError('need at least two functions to compose')
# get most inner function
composed = []
print("appending func 1")
composed.append(funcs[-1])
# pop last and reverse
funcs = funcs[:-1][::-1]
i = 1
for func in funcs:
i += 1
print("appending func %s" % i)
composed.append(lambda *args, **kwargs: func(composed[-1](*args,**kwargs)))
return composed[-1]
def inc(x):
print("inc called with %s" % x)
return x+1
def dbl(x):
print("dbl called with %s" % x)
return x*2
def inv(x):
print("inv called with %s" % x)
return x*(-1)
if __name__ == '__main__':
comp(inv,dbl,inc)(2)
回溯(如果有帮助):
appending func 1
appending func 2
appending func 3
Traceback (most recent call last):
File "comp.py", line 31, in <module>
comp(inv,dbl,inc)(2)
File "comp.py", line 17, in <lambda>
composed.append(lambda *args, **kwargs: func(composed[-1](*args,**kwargs)))
File "comp.py", line 17, in <lambda>
composed.append(lambda *args, **kwargs: func(composed[-1](*args,**kwargs)))
File "comp.py", line 17, in <lambda>
composed.append(lambda *args, **kwargs: func(composed[-1](*args,**kwargs)))
(...)
File "comp.py", line 17, in <lambda>
composed.append(lambda *args, **kwargs: func(composed[-1](*args,**kwargs)))
RuntimeError: maximum recursion depth exceeded while calling a Python object