Python 三目运算, 2 种表达方式返回结果为什么不一样?

2017-06-30 00:30:08 +08:00
 fuxkcsdn

python 萌新(学了 3 个月左右还算吗)

一直用 condition and true or false 这个三目运算表达式(因为比 true if condition else false 少一个字符...) 今天码程序的时候发现用前一种表达式得到的结果非预期

Python 3.4.2 和 2.7.9 测试过都一样

from dogpile.cache import make_region
from dogpile.cache.api import NoValue

cache = make_region().configure(
    'dogpile.cache.dbm', arguments={'filename': '/tmp/cache.dbm'})
                                                     
session = cache.get('NO_EXISTS_KEY')                 
                                                     
print(isinstance(session, NoValue) and None or session)
print(None if isinstance(session, NoValue) else session)

# Output <dogpile.cache.api.NoValue object at 0x107611c10>
# Output None
3833 次点击
所在节点    Python
16 条回复
for4
2017-06-30 00:37:04 +08:00
isinstance(session, NoValue) and None or session

( isinstance(session, NoValue) and None ) === None

None or session => session
zjuhwc
2017-06-30 00:42:17 +08:00
你都写了
condition and true or false,
你的用法里第二个是 None,并不是一个 true。
关键是理解 python 里的真值有哪些,and or 只是利用了逻辑短路特性模拟的三目运算符,可读性不好,推荐还是用 if else 的写法
Xs0ul
2017-06-30 00:44:13 +08:00
以我的理解,condition and true or false 只是按照 python 语法写出的一个普通表达式。

isinstance(session, NoValue): True
True and None: None
None or session: session

所以 print 出了 session

第二个是 None。这两个写法并不是等价的。
binux
2017-06-30 01:31:16 +08:00
不要用 and or 当三目运算符
skydiver
2017-06-30 02:07:38 +08:00
因为本来就不等价
NoAnyLove
2017-06-30 03:31:30 +08:00
不要乱用`cond and or`,这是官方不推荐的用法。用`A if cond else B`
wwqgtxx
2017-06-30 06:54:55 +08:00
谁说过 and or 是三目运算符了
bfbd
2017-06-30 07:32:03 +08:00
换一下顺序,把 None 放在最后。 (not isinstance(session, NoValue)) and session or None,
CYKun
2017-06-30 08:48:17 +08:00
condition and ret,你这是 javascript 的习惯写法吧,python 里没怎么见过这么写的。

第一次见到这种写法的时候懵逼了半天,不得不承认 js 程序员脑洞清奇。
lrh3321
2017-06-30 08:52:23 +08:00
"谁说过 and or 是三目运算符了" +1
ipwx
2017-06-30 08:52:24 +08:00
A and B <=> B if A else A
A or B <=> A if A else B
Lycnir
2017-06-30 08:53:00 +08:00
如果不能明确返回,就像 1 楼老实的是括号
VicYu
2017-06-30 09:06:56 +08:00
NaVient
2017-06-30 09:22:46 +08:00
你应该需要的是 a if True else b
minvacai
2017-06-30 09:25:16 +08:00
我想问既然是 javascript 为什么不用 condition ? a : b
cxyfreedom
2017-06-30 09:28:05 +08:00
第一种基本就没写过

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/372054

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX