`is`运算符是否在Python中使用__magic__方法? [英] Does the `is` operator use a __magic__ method in Python?

查看:65
本文介绍了`is`运算符是否在Python中使用__magic__方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

is 运算符用于身份验证.

The is operator is used test for identity.

我想知道is运算符和id()函数是否以==调用__eq__的方式调用任何__magic__方法.

I was wondering if the is operator and id() function call any __magic__ method, the way == calls __eq__.

我很有趣地签出__hash__:

class Foo(object):
    def __hash__(self):
        return random.randint(0, 2 ** 32)

a = Foo()
b = {}
for i in range(5000):
    b[a] = i

考虑字典bb[a]

以后每次d[a]查找都是KeyError或随机整数.

Every subsequent lookup of d[a] is either a KeyError or a random integer.

但作为有关特殊方法的文档状态

[ 的默认实现] x.__hash__()返回id(x).

[the default implementation of] x.__hash__() returns id(x).

因此两者之间存在 关系,但反之亦然.

So there is relation between the two, but just the other way around.

我在这里的isid上看到了许多问题,以及困惑的人,但是我找不到这个答案.

I've seen many questions on is and id here, and the answers have helped many confused minds, but I couldn't find an answer to this one.

推荐答案

否,is是直接指针比较,而id只是将转换为long的对象的地址返回.

No, is is a straight pointer comparison, and id just returns the address of the object cast to a long.

来自 ceval.c :

case PyCmp_IS:
    res = (v == w);
    break;
case PyCmp_IS_NOT:
    res = (v != w);
    break;

vw就是PyObject *.

来自 bltinmodule.c :

static PyObject *
builtin_id(PyObject *self, PyObject *v)
{
    return PyLong_FromVoidPtr(v);
}

PyDoc_STRVAR(id_doc,
"id(object) -> integer\n\
\n\
Return the identity of an object. This is guaranteed to be unique among\n\
simultaneously existing objects. (Hint: it's the object's memory address.)");

这篇关于`is`运算符是否在Python中使用__magic__方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆