[英]How to execute many functions one after the other
我想一個接一個地執行許多功能。 每個函數返回True或False。 因此,如果一個函數返回True,我想執行下一個。 等等...
所有功能都不需要相同的參數。
現在我有類似的東西:
res=function1()
if res:
res=function2()
if res:
res=function2()
它持續進行20種功能。 有一個更好的方法嗎 ?
先感謝您...
好吧,您可以定義自己的方式來執行此操作,但是我會那樣做:
my_functions = (
(my_func1, [2, 5], {'kwarg1': 'val1'}),
# ...
)
for function, args, kwargs in my_functions:
if not function(*args, **kwargs):
break
根據評論進行編輯。 真知灼見!
我可能會使用partial
來制作可以循環的零參數函數(而不是帶有該函數及其參數的某種結構):
functions = [
functools.partial(func1, arg1a, arg1b),
functools.partial(func2),
functools.partial(func3, keyword_a=kwarg3a, keyword_b=kwarg3b)
]
然后,不必將其放入list
並進行遍歷,您只需調用all
:
retval = all(func() for func in (
functools.partial(func1, arg1a, arg1b),
functools.partial(func2),
functools.partial(func3, keyword_a=kwarg3a, keyword_b=kwarg3b)
))
這將返回False
盡快的功能之一返回False
(或任何虛假-Y),或運行所有的功能和返回True
,如果他們都返回True
(或任何真正-Y)。 正如文檔所說,它等效於:
def all(iterable):
for element in iterable:
if not element:
return False
return True
值得在另一個答案中比較partial
s和tuple
s,它們在它們的定義方式和調用方式上都充當偽partials:
f1 = functools.partial(func, arg1, arg2, kw1=kwarg1, kw2=kwarg2)
f2 = (func1, (arg1a, arg1b), {'kw1': kwarg1, 'kw2': kwarg2 })
f1()
f2[0](*f2[1], **f2[2])
顯然,您可以(並且應該,如aemdy的回答那樣)使調用通過元組拆包更具可讀性,但它永遠不會像使用真正的局部調用那樣簡單。
您可以利用and
運算符的短路行為:
function1() and function2() and function3() and ...
function2
才會被調用,如果function1
返回True
, function3
將只能被稱為如果function1
和function2
返回True
,等等。
不過,它不一定具有Python風格。
由於您總是分配給res
,因此您也可以僅將if
s保持平坦:
res = function1()
if res:
res = function2()
if res:
res = function3()
可以認為它更具可讀性,但確實浪費了很多垂直空間。 至少你沒有嵌套if
兩大打深,雖然。
無需太復雜:
res = function1()
res = res and function2()
res = res and function3()
...
這看起來有些奇怪,但是可以做您想做的事,而不必繞開函數調用自己,將其自身折疊成詞典列表或其他內容。 這只是寫Cairnarvon答案的一種較長的方法:
res = (
function1() and
function2() and
function3() and
...
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.