[英]Python equivalent of Perl's idiom do this or that, usually known as “or die”?
在Perl中,做一些像function() || alternative()
這樣的事情很常見 function() || alternative()
。 如果第一個返回false,它將運行第二個。
如何在Python中輕松實現?
更新
示例(偽代碼):
x = func() or raise exeption
x = func() or print(x)
func() or print something
如果可能的解決方案應該與Python 2.5+一起使用
注意:有一個隱含的假設是你不能修改func()來引發異常,也不能編寫包裝器。
使用or
:Python對布爾表達式使用短路評估 :
function() or alternative()
如果function
重新生成True,則確定此表達式的最終值,並且根本不評估alternative
值。
你可以使用or
:
function() or alternative()
另外, PEP 308中定義了條件表達式:
x = 5 if condition() else 0
這在表達式中有時很有用,而且更具可讀性。
function() or alternative()
機制完全一樣。
嘗試用or
:
>>> def bye():
return 3
>>> print bye() or 342432
3
不幸的是,這在Perl中不起作用,因為在Perl中,在my $c = $d || 45;
類的賦值之后 my $c = $d || 45;
如果$d
未定義,你在$c
的值為45。 在Python中,您會收到錯誤NameError: name 'd' is not defined
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.