本文介绍了如何在Python中实现'is'关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

... 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'关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 16:40