简体   繁体   English

Python相当于Perl的习惯做这个或那个,通常被称为“或死”?

[英]Python equivalent of Perl's idiom do this or that, usually known as “or die”?

IN Perl it's quite common to do things like function() || alternative() 在Perl中,做一些像function() || alternative()这样的事情很常见 function() || alternative() . function() || alternative() If the first returns false it will run the second one. 如果第一个返回false,它将运行第二个。

How can this be easily implemented in Python? 如何在Python中轻松实现?

Update 更新

Examples (pseudocode): 示例(伪代码):

x = func() or raise exeption
x = func() or print(x)
func() or print something

If possible solutions should work with Python 2.5+ 如果可能的解决方案应该与Python 2.5+一起使用

Note: There is an implied assumption that you cannot modify the func() to raise exceptions, nor to write wrappers. 注意:有一个隐含的假设是你不能修改func()来引发异常,也不能编写包装器。

Use or : Python uses short circuit evaluation for boolean expressions: 使用or :Python对布尔表达式使用短路评估

function() or alternative()

If function returs True, the final value of this expression is determined and alternative is not evaluated at all. 如果function重新生成True,则确定此表达式的最终值,并且根本不评估alternative值。

you can use or : 你可以使用or

function() or alternative()

also, there is conditional expression defined in PEP 308 : 另外, PEP 308中定义了条件表达式:

x = 5 if condition() else 0

Which is sometimes useful in expressions and bit more readable. 这在表达式中有时很有用,而且更具可读性。

function() or alternative()

机制完全一样。

try with or : 尝试用or

>>> def bye():
  return 3

>>> print bye() or 342432
3

Unfortunately, this does not work like in Perl, because in Perl, after an assignment like my $c = $d || 45; 不幸的是,这在Perl中不起作用,因为在Perl中,在my $c = $d || 45;类的赋值之后 my $c = $d || 45; you have in $c the value 45 if $d is undefined. 如果$d未定义,你在$c的值为45。 In Python you get an error NameError: name 'd' is not defined 在Python中,您会收到错误NameError: name 'd' is not defined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM