我想寫一種CPS代碼更高的功能。他們應該獲取一個函數代碼,將其封裝在對象中並添加用於組合這些對象的方法。更多功能python
事情是這樣的:
myFunction=MyFunction(
a = b+c
print(c)
return a)
但只有一個匿名函數Python的表達 - 拉姆達聲明。它適合不太好。
Python是一種功能強大的語言,它有不同的表達式:裝飾器,eval等...有沒有一種好的方法來編寫像上面例子中的匿名函數?
其他方法是擴展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。我有一個錯誤。我應該如何在任何情況下放置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
爲什麼它必須是匿名的? – KillianDS 2012-04-19 19:10:19
複雜和單行不適合python zen – KurzedMetal 2012-04-19 19:11:04
每種語言都不一樣。不要試圖用Python來編寫功能代碼,就像用另一種語言完全一樣。 – agf 2012-04-19 19:11:07