30

is 语法带来的误读

 5 years ago
source link: http://www.hongweipeng.com/index.php/archives/1622/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

起步

Python 的成功一个原因是它的可读性,代码清晰易懂,更容易被人类所理解,但有时可读性会产生误解。

假如要判断一个变量是不是 17,那可以:

if x is 17:

x 是 17 肯定是比 x == 17 更加口语化的。

is的误解

但是如果你尝试:

if name is "weapon":

这个判断不见得管用。 is 用来检查左侧和右侧是否是完全相同的对象。如果有两个不同的字符串对象,每个对象的值是相同的,应该使用 == 来判断,因为 is 的用法与口语上的区别挺大的:

if 999 + 1 is 1000:  # False

正因为这样的误解,在 if 判断条件上容易让初学者掉坑:

answer = 'yes'
if answer is 'y' or 'yes':

你会发现不管变量是什么值,判断都是为真。因为 is 的优先级高,相当于 if (answer is 'y') or ('yes')

正确的方法应该是 if answer == 'y' or answer == 'yes' 或者 if answer in ('y', 'yes')

is not 上的混淆

>>> 'something' is not None
True
>>> 'something' is (not None)
False

is not 是一个二元运算符,应该视为一个整体,不要因为中间空格而当成两个词。底层上,它们也是一个操作符,CPython 将 s is not None 翻译成的字节码为:

6 LOAD_NAME                0 (s)
 8 LOAD_CONST               1 (None)
10 COMPARE_OP               9 (is not)

is not 是对 is 相对应的操作符。也可以视为是将 is 判断的结果再进行取反。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK