Python 的海象操作符,整体使用起来感觉咋样?

讨论 未结 8 94
haoliang
haoliang 会员 2022年9月1日 00:39 发表
<pre><code>def fn_with_long_name(n): return n def case_1(): if (x := fn_with_long_name(2)) == 2: print("a", x) else: print("b", x) # 什么?这里多了个变量 x ? def case_2(): x = 100 if (x := fn_with_long_name(2)) == 2: print("a", x) else: print("b", x) # 啊? x 在上面哪改了 assert x != 100 def case_3(): x = fn_with_long_name(3) if x == 2: print("a", x) else: print("b", x) </code></pre> <p>我觉得声明变量藏在条件语句中,这也太难找了吧, 一不留神多了个变量;更怕覆盖了之前的值,因为这种写法让我以为声明的变量的作用域是 if 块。 所以我的暴论是:我各种情况下一概不用,也不看它的适用场景了;毕竟 python zen 中说:</p> <ul> <li>Explicit is better than implicit.</li> <li>Special cases aren't special enough to break the rules.</li> <li>There should be one-- and preferably only one --obvious way to do it.</li> </ul>
收藏(0)  分享
相关标签: 灌水交流
注意:本文归作者所有,未经作者允许,不得转载
8个回复
  • abersheeran
    2022年9月1日 00:39
    本来就是用来简化 var = ...... if var == .....: 这种结构的,你来一句“我以为作用域在 if 块内”🤔
    0 0
  • tairan2006
    2022年9月1日 01:11
    python 本来就没有块作用域啊。。你这
    0 0
  • princelai
    2022年9月1日 01:39
    用得很好,但是还挺好用的,除了条件语句变得很长,另外你这个情况为什么不用 match case 语句
    0 0
  • Virace
    2022年9月1日 03:40
    挺好用的,就是要熟悉语法之后,就好了。 变量名规范,自己也看得舒服,没什么毛病。 真要从头 x 到尾然后说不好用,那只能说确实不适合这种情况= =
    0 0