“是”怎么样? Python 中实现的关键字?
...可用于字符串相等的 is
关键字。
>>> s = 'str'
>>> s is 'str'
True
>>> s is 'st'
False
我尝试了 __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 self.s == s
...
>>>
>>> m = MyString()
>>> m is 'ss'
False
>>> m is 'string' # <--- Expected to work, but again failed
False
>>>
... the is
keyword that can be used for equality in strings.
>>> s = 'str'
>>> s is 'str'
True
>>> s is 'st'
False
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
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
仅当字符串被保留时,使用
is
测试字符串才有效。除非你真的知道自己在做什么并且明确地interned字符串,否则你永远不应该< /em> 在字符串上使用is
。是
测试身份,而不是平等。这意味着 Python 只是比较对象所在的内存地址。is
基本上回答了“同一个对象有两个名称吗?”的问题。 - 超载是没有意义的。例如,
("a" * 100) 是 ("a" * 100)
是False。通常Python将每个字符串写入不同的内存位置,实习主要发生在字符串文字上。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 useis
on strings.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.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.is
运算符相当于比较id(x)
值。例如:id
当前实现为使用指针作为比较。所以你不能重载is
本身,而且据我所知你也不能重载id
。所以,你不能。在 python 中不常见,但确实如此。
The
is
operator is equivalent to comparingid(x)
values. For example:id
is currently implemented to use pointers as the comparison. So you can't overloadis
itself, and AFAIK you can't overloadid
either.So, you can't. Unusual in python, but there it is.
Python
is
关键字测试对象身份。您不应该使用它来测试字符串相等性。它似乎经常工作,因为 Python 实现,就像许多非常高级语言的实现一样,执行字符串的“驻留”。也就是说,字符串文字和值在内部保存在哈希列表中,并且相同的字符串文字和值将呈现为对同一对象的引用。 (这是可能的,因为 Python 字符串是不可变的)。但是,与任何实现细节一样,您不应依赖于此。如果要测试相等性,请使用 == 运算符。如果你真的想测试对象标识,那么使用 is ,我很难想出一个你应该关心字符串对象标识的情况。不幸的是,由于前面提到的驻留,您不能指望两个字符串是否在某种程度上“故意”相同的对象引用。
The Python
is
keyword tests object identity. You should NOT use it to test for string equality. It may seem to work frequently because Python implementations, like those of many very high level languages, performs "interning" of strings. That is to say that string literals and values are internally kept in a hashed list and those which are identical are rendered as references to the same object. (This is possible because Python strings are immutable).However, as with any implementation detail, you should not rely on this. If you want to test for equality use the == operator. If you truly want to test for object identity then use
is
--- and I'd be hard-pressed to come up with a case where you should care about string object identity. Unfortunately you can't count on whether two strings are somehow "intentionally" identical object references because of the aforementioned interning.is
关键字比较对象(或者更确切地说,比较两个引用是否指向同一对象)。我认为这就是为什么没有机制来提供您自己的实现。
有时它恰好适用于字符串,因为 Python 会“巧妙地”存储字符串,这样当您创建两个相同的字符串时,它们就会存储在一个对象中。
您有望在一个简单的“复制”示例中看到参考与数据的比较:
The
is
keyword compares objects (or, rather, compares if two references are to the same object).Which is, I think, why there's no mechanism to provide your own implementation.
It happens to work sometimes on strings because Python stores strings 'cleverly', such that when you create two identical strings they are stored in one object.
You can hopefully see the reference vs data comparison in a simple 'copy' example:
如果您不怕搞乱字节码,您可以拦截并修补
COMPARE_OP
与8 ("is")
参数,以在正在比较的对象上调用钩子函数。查看dis
模块文档以了解启动信息。如果有人会执行
id(a) == id(b)
而不是a is b<,也不要忘记拦截
__builtin__.id()
/代码>。If you are not afraid of messing up with bytecode, you can intercept and patch
COMPARE_OP
with8 ("is")
argument to call your hook function on objects being compared. Look atdis
module documentation for start-in.And don't forget to intercept
__builtin__.id()
too if someone will doid(a) == id(b)
instead ofa is b
.'is' 比较对象标识,而 == 比较值。
例子:
'is' compares object identity whereas == compares values.
Example:
当字符串以“-”开头时,无法将字符串变量与字符串值以及两个字符串变量进行比较。我的Python版本是2.6.6
is fails to compare a string variable to string value and two string variables when the string starts with '-'. My Python version is 2.6.6
您不能重载
is
运算符。您要重载的是==
运算符。这可以通过在类中定义 __eq__ 方法来完成。You can't overload the
is
operator. What you want to overload is the==
operator. This can be done by defining a__eq__
method in the class.您正在使用身份比较。 == 可能就是您想要的。例外情况是当您想要检查一个项目和另一个项目是否是完全相同的对象并且位于相同的内存位置时。在您的示例中,该项目不相同,因为一个项目的类型(my_string)与另一个项目(字符串)不同。另外,Python 中不存在诸如 someclass.
__is__
这样的东西(当然,除非你自己把它放在那里)。如果存在的话,将对象与 is 进行比较,仅仅比较内存位置是不可靠的。当我第一次遇到 is 关键字时,它也让我感到困惑。我本以为 is 和 == 没有什么不同。他们在许多对象上从解释器产生了相同的输出。这种类型的假设实际上正是...的用途。这相当于 Python 中的“嘿,不要弄错这两个对象。它们是不同的。”,这基本上就是 [无论是谁纠正了我] 所说的。措辞有很大不同,但一点 == 另一点。
这
一些有用的例子和一些文字来帮助解决有时令人困惑的差异
访问来自 python.org 邮件主机的文档,作者为“Danny” Yoo”
,或者,如果它处于离线状态,请使用我用它的主体制作的未列出的pastebin。
如果它们在大约 20 个蓝月(蓝月是真实事件)中都下降了,我将引用代码示例
You are using identity comparison. == is probably what you want. The exception to this is when you want to be checking if one item and another are the EXACT same object and in the same memory position. In your examples, the item's aren't the same, since one is of a different type (my_string) than the other (string). Also, there's no such thing as someclass.
__is__
in python (unless, of course, you put it there yourself). If there was, comparing objects with is wouldn't be reliable to simply compare the memory locations.When I first encountered the is keyword, it confused me as well. I would have thought that is and == were no different. They produced the same output from the interpreter on many objects. This type of assumption is actually EXACTLY what is... is for. It's the python equivalent "Hey, don't mistake these two objects. they're different.", which is essentially what [whoever it was that straightened me out] said. Worded much differently, but one point == the other point.
the
for some helpful examples and some text to help with the sometimes confusing differences
visit a document from python.org's mail host written by "Danny Yoo"
or, if that's offline, use the unlisted pastebin I made of it's body.
in case they, in some 20 or so blue moons (blue moons are a real event), are both down, I'll quote the code examples
在比较对象时,is 关键字很容易出现断言错误。例如,对象a和b可能拥有相同的值并共享相同的内存地址。因此,执行
is 将评估为
但如果
评估为
您可能应该检查
并且
这些可能不同并且是失败的原因。
Assertion Errors can easily arise with is keyword while comparing objects. For example, objects a and b might hold same value and share same memory address. Therefore, doing an
is going to evaluate to
But if
evaluates to
you should probably check
and
These might be different and a reason for failure.
因为字符串实习,这可能看起来很奇怪:
Because string interning, this could look strange: