我注意到我写的一个Python脚本是松散的,并将其追溯到一个无限循环,循环条件是while line is not ''.在调试器中运行它,事实证明该行''.当我改为!=''而不是is not '',它工作得很好.
另外,通常认为默认情况下使用'=='会更好,即使在比较int或Boolean值时也是如此?我一直喜欢使用'是'因为我发现它更美观和pythonic(这就是我陷入这个陷阱...),但我想知道它是否只是为了保留当你关心找到两个具有相同id的对象.
为什么以下在Python中出现意外行为?
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
Run Code Online (Sandbox Code Playgroud)
我使用的是Python 2.5.2.尝试一些不同版本的Python,似乎Python 2.3.3显示了99到100之间的上述行为.
基于以上所述,我可以假设Python在内部实现,使得"小"整数以不同于大整数的方式存储,is运算符可以区分.为什么泄漏抽象?当我不知道它们是否是数字时,比较两个任意对象以查看它们是否相同的更好的方法是什么?
... is可用于字符串中相等的关键字.
>>> s = 'str'
>>> s is 'str'
True
>>> s is 'st'
False
Run Code Online (Sandbox Code Playgroud)
我试过了两个__is__(),__eq__()但他们没有工作.
>>> class MyString:
... def __init__(self):
... self.s = 'string'
... def __is__(self, s):
... return self.s == s
...
>>>
>>>
>>> m = MyString()
>>> m is 'ss'
False
>>> m is 'string' # <--- Expected to work
False
>>>
>>> class MyString:
... def __init__(self):
... self.s = 'string'
... def __eq__(self, s):
... return …Run Code Online (Sandbox Code Playgroud)