“是”怎么样? Python 中实现的关键字?

发布于 2024-09-04 22:20:26 字数 836 浏览 9 评论 0原文

...可用于字符串相等的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

零度℉ 2024-09-11 22:20:27

仅当字符串被保留时,使用 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 use is 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.

岛徒 2024-09-11 22:20:27

is 运算符相当于比较 id(x) 值。例如:

>>> s1 = 'str'
>>> s2 = 'str'
>>> s1 is s2
True
>>> id(s1)
4564468760
>>> id(s2)
4564468760
>>> id(s1) == id(s2)  # equivalent to `s1 is s2`
True

id当前实现为使用指针作为比较。所以你不能重载 is 本身,而且据我所知你也不能重载 id

所以,你不能。在 python 中不常见,但确实如此。

The is operator is equivalent to comparing id(x) values. For example:

>>> s1 = 'str'
>>> s2 = 'str'
>>> s1 is s2
True
>>> id(s1)
4564468760
>>> id(s2)
4564468760
>>> id(s1) == id(s2)  # equivalent to `s1 is s2`
True

id is currently implemented to use pointers as the comparison. So you can't overload is itself, and AFAIK you can't overload id either.

So, you can't. Unusual in python, but there it is.

娇女薄笑 2024-09-11 22:20:27

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.

挽梦忆笙歌 2024-09-11 22:20:27

is 关键字比较对象(或者更确切地说,比较两个引用是否指向同一对象)。

我认为这就是为什么没有机制来提供您自己的实现。

有时它恰好适用于字符串,因为 Python 会“巧妙地”存储字符串,这样当您创建两个相同的字符串时,它们就会存储在一个对象中。

>>> a = "string"
>>> b = "string"
>>> a is b
True
>>> c = "str"+"ing"
>>> a is c
True

您有望在一个简单的“复制”示例中看到参考与数据的比较:

>>> a = {"a":1}
>>> b = a
>>> c = a.copy()
>>> a is b
True
>>> a is c
False

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.

>>> a = "string"
>>> b = "string"
>>> a is b
True
>>> c = "str"+"ing"
>>> a is c
True

You can hopefully see the reference vs data comparison in a simple 'copy' example:

>>> a = {"a":1}
>>> b = a
>>> c = a.copy()
>>> a is b
True
>>> a is c
False
渔村楼浪 2024-09-11 22:20:27

如果您不怕搞乱字节码,您可以拦截并修补 COMPARE_OP8 ("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 with 8 ("is") argument to call your hook function on objects being compared. Look at dis module documentation for start-in.

And don't forget to intercept __builtin__.id() too if someone will do id(a) == id(b) instead of a is b.

御弟哥哥 2024-09-11 22:20:27

'is' 比较对象标识,而 == 比较值。

例子:

a=[1,2]
b=[1,2]
#a==b returns True
#a is b returns False

p=q=[1,2]
#p==q returns True
#p is q returns True

'is' compares object identity whereas == compares values.

Example:

a=[1,2]
b=[1,2]
#a==b returns True
#a is b returns False

p=q=[1,2]
#p==q returns True
#p is q returns True
琴流音 2024-09-11 22:20:27

当字符串以“-”开头时,无法将字符串变量与字符串值以及两个字符串变量进行比较。我的Python版本是2.6.6

>>> s = '-hi'
>>> s is '-hi'
False 
>>> s = '-hi'
>>> k = '-hi'
>>> s is k 
False
>>> '-hi' is '-hi'
True

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

>>> s = '-hi'
>>> s is '-hi'
False 
>>> s = '-hi'
>>> k = '-hi'
>>> s is k 
False
>>> '-hi' is '-hi'
True
枕梦 2024-09-11 22:20:27

您不能重载 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.

久夏青 2024-09-11 22:20:27

您正在使用身份比较。 == 可能就是您想要的。例外情况是当您想要检查一个项目和另一个项目是否是完全相同的对象并且位于相同的内存位置时。在您的示例中,该项目不相同,因为一个项目的类型(my_string)与另一个项目(字符串)不同。另外,Python 中不存在诸如 someclass.__is__ 这样的东西(当然,除非你自己把它放在那里)。如果存在的话,将对象与 is 进行比较,仅仅比较内存位置是不可靠的。

当我第一次遇到 is 关键字时,它也让我感到困惑。我本以为 is 和 == 没有什么不同。他们在许多对象上从解释器产生了相同的输出。这种类型的假设实际上正是...的用途。这相当于 Python 中的“嘿,不要弄错这两个对象。它们是不同的。”,这基本上就是 [无论是谁纠正了我] 所说的。措辞有很大不同,但一点 == 另一点。


一些有用的例子和一些文字来帮助解决有时令人困惑的差异
访问来自 python.org 邮件主机的文档,作者为“Danny” Yoo”

,或者,如果它处于离线状态,请使用我用它的主体制作的未列出的pastebin

如果它们在大约 20 个蓝月(蓝月是真实事件)中都下降了,我将引用代码示例

###
>>> my_name = "danny"
>>> your_name = "ian"
>>> my_name == your_name
0                #or False
###

###
>>> my_name[1:3] == your_name[1:3]
1    #or True
###

###
>>> my_name[1:3] is your_name[1:3]
0
###

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

###
>>> my_name = "danny"
>>> your_name = "ian"
>>> my_name == your_name
0                #or False
###

###
>>> my_name[1:3] == your_name[1:3]
1    #or True
###

###
>>> my_name[1:3] is your_name[1:3]
0
###
花开雨落又逢春i 2024-09-11 22:20:27

在比较对象时,is 关键字很容易出现断言错误。例如,对象ab可能拥有相同的值并共享相同的内存地址。因此,执行

>>> a == b

is 将评估为

True

但如果

>>> a is b

评估为

False

您可能应该检查

>>> type(a)

并且

>>> type(b)

这些可能不同并且是失败的原因。

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

>>> a == b

is going to evaluate to

True

But if

>>> a is b

evaluates to

False

you should probably check

>>> type(a)

and

>>> type(b)

These might be different and a reason for failure.

方圜几里 2024-09-11 22:20:27

因为字符串实习,这可能看起来很奇怪:

a = 'hello'
'hello' is a  #True

b= 'hel-lo'
'hel-lo' is b #False

Because string interning, this could look strange:

a = 'hello'
'hello' is a  #True

b= 'hel-lo'
'hel-lo' is b #False
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文