我猜这是 Python 古老版本(2.4 或更早)的一个遗留问题,当时该语言还没有三目运算符。根据 Python 编程 FAQ 的说法:
Is there an equivalent of C’s ”?:” ternary operator?
Yes, there is. The syntax is as follows:
[on_true] if [expression] else [on_false] x, y = 50, 25 small = x if x < y else y
Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:
[expression] and [on_true] or [on_false]
However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.
现在,这个问题中的行可以写成以下两种方式之一:
# Option 1
oname = args if args else '_'
# Option 2
oname = args or '_'
[value] and [value] or [alternate_value]
语法。 - Jonah Bishoponame = args or '_'
? - L3viathan
args or '_'
。 - Willem Van Onsema if b else c
和a or b
,我只是想知道我看到的是否有逻辑... - elyashivargs
是“真实的”,则oname
为args
,否则为'_'
。 - Willem Van Onsem