【发布时间】:2012-04-19 19:08:34
【问题描述】:
我想编写一种 CPS 代码的高级函数。他们应该获取一个功能代码,将其封装在对象中,并添加组合这些对象的方法。
类似这样的:
myFunction=MyFunction(
a = b+c
print(c)
return a)
但是对于匿名函数,只有一个 Python 表达式—— lambda 语句。它不太适合。
Python 是一门强大的语言,它有不同的表达方式:装饰器、eval 等......有没有像上面提到的例子那样编写匿名函数的好方法?
另一种方法是使用特殊函数(如 monadic bind 和 return)扩展 lambda 表达式,以及用于编写单行复杂表达式的其他高阶函数。
主要目的是创建自定义的抛出控制表达式。
class TimeoutExpression:
def __init__(self,name,function,timeout):
...
def eval(self):
""" eval functions, print result and error message
if functions failed to calculate in time """
...
def andThen(self,otherExpression):
""" create complex sequential expression"
...
def __call__(self):
...
它的使用方式如下:
TimeoutExpression( time consuming calculation ).andThen(
file object access).andThen(
other timer consuming calcualtion )
创建自定义控制流构造的最佳 Python 惯用方式是什么?
我已阅读讨论:How to make an anonymous function in Python without Christening it? 提到了几个采用相同方法的决定:从三重引号字符串生成函数。 虽然行为完全正确,但似乎很麻烦。它是目前设计的最佳方法吗?
更新:
有人告诉我没有问题,python 允许你在任何上下文中使用 def。我假设我的 python 经验欺骗了我,并尝试按照建议在任何范围内使用 def 。我有一个错误。我应该如何将 def 放在任何上下文中?
def compose(f):
return lambda k: lambda x: f(k(x))
test = compose( def sqr(x) :
print ("sqr "+str(x))
return x*x
return sqr) ( def x2(x):
print("x2 "+str(x))
return x*2
return x2 )
错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "anonFunction.py", line 4
test = compose( def sqr(x) :
^
SyntaxError: invalid syntax
【问题讨论】:
-
为什么一定要匿名?
-
复杂单行不适合python zen
-
每种语言都不同。不要尝试使用 Python 编写函数式代码,就像用另一种语言编写函数式代码一样。
标签: python functional-programming anonymous-function