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
1 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 |
2 zjuhwc 2017-06-30 00:42:17 +08:00 via iPhone 你都写了 condition and true or false, 你的用法里第二个是 None,并不是一个 true。 关键是理解 python 里的真值有哪些,and or 只是利用了逻辑短路特性模拟的三目运算符,可读性不好,推荐还是用 if else 的写法 |
![]() | 3 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。这两个写法并不是等价的。 |
![]() | 4 binux 2017-06-30 01:31:16 +08:00 不要用 and or 当三目运算符 |
![]() | 5 skydiver 2017-06-30 02:07:38 +08:00 via Android 因为本来就不等价 |
6 NoAnyLove 2017-06-30 03:31:30 +08:00 不要乱用`cond and or`,这是官方不推荐的用法。用`A if cond else B` |
![]() | 7 wwqgtxx 2017-06-30 06:54:55 +08:00 via iPhone 谁说过 and or 是三目运算符了 |
![]() | 8 bfbd 2017-06-30 07:32:03 +08:00 换一下顺序,把 None 放在最后。 (not isinstance(session, NoValue)) and session or None, |
9 CYKun 2017-06-30 08:48:17 +08:00 via Android condition and ret,你这是 Javascript 的习惯写法吧,python 里没怎么见过这么写的。 第一次见到这种写法的时候懵逼了半天,不得不承认 js 程序员脑洞清奇。 |
![]() | 10 lrh3321 2017-06-30 08:52:23 +08:00 "谁说过 and or 是三目运算符了" +1 |
![]() | 11 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 |
![]() | 12 Lycnir 2017-06-30 08:53:00 +08:00 如果不能明确返回,就像 1 楼老实的是括号 |
13 VicYu 2017-06-30 09:06:56 +08:00 |
![]() | 14 NaVient 2017-06-30 09:22:46 +08:00 你应该需要的是 a if True else b |
![]() | 15 minvacai 2017-06-30 09:25:16 +08:00 via Android 我想问既然是 Javascript 为什么不用 condition ? a : b |
![]() | 16 cxyfreedom 2017-06-30 09:28:05 +08:00 via iPhone 第一种基本就没写过 |