问题描述
... is
关键字,可用于字符串相等。
... the is
keyword that can be used for equality in strings.
>>> s = 'str'
>>> s is 'str'
True
>>> s is 'st'
False
我都尝试了 __ is __( )
和 __ eq __()
,但它们不起作用。
I tried both __is__()
and __eq__()
but they didn't work.
>>> 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 self.s == s
...
>>>
>>> m = MyString()
>>> m is 'ss'
False
>>> m is 'string' # <--- Expected to work, but again failed
False
>>>
推荐答案
使用 is测试字符串
仅在插入字符串时有效。除非您真的知道自己在做什么,并且明确,否则应该永远在字符串上使用 is
。
Testing strings with is
only works when the strings are interned. Unless you really know what you're doing and explicitly interned the strings you should never use is
on strings.
是
测试的是身份,而不是平等。这意味着Python只是比较对象驻留的内存地址。是
基本上回答了以下问题:同一对象有两个名称吗? -重载是没有意义的。
is
tests for identity, not equality. That means Python simply compares the memory address a object resides in. is
basically answers the question "Do I have two names for the same object?" - overloading that would make no sense.
例如,( a * 100)为( a * 100)
为 False 。通常,Python将每个字符串写入不同的内存位置,大多数情况下是对字符串文字进行实习。
For example, ("a" * 100) is ("a" * 100)
is False. Usually Python writes each string into a different memory location, interning mostly happens for string literals.
这篇关于如何在Python中实现'is'关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!