Is and ID in Python

Source: Internet
Author: User

(Ob1 is OB2) equivalent to (ID (ob1) = = ID (ob2))

First the ID function can get the memory address of the object, if the memory address of the two objects is the same, then the two objects must be an object. is equivalent to IS. Python source code is proof.

1234567891011 static PyObject * cmp_outcome(int op, register PyObject *v, register PyObject *w){ int res = 0; switch (op) { case PyCmp_IS:  res = (v == w); break; case PyCmp_IS_NOT:res = (v != w); break;

But look at the code below, how does this happen?

123456789101112131415161718 In [1]: def bar(self, x):...:     return self.x + y...: In [2]: class Foo(object):...:     x = 9...:     def __init__(self ,x):...:         self.x = x...:     bar = bar...:     In [3]: foo = Foo(5)In [4]: foo.bar is Foo.barOut[4]: FalseIn [5]: id(foo.bar) == id(Foo.bar)Out[5]: True

Two objects are judged by is false, but the ID is true, which is inconsistent with the facts we know, how to explain this phenomenon? The best solution to this situation is to call the DIS module to see what the two comparison statements have done.

12345678910111213141516171819202122232425 In [7]: dis.dis("id(foo.bar) == id(Foo.bar)")          0 BUILD_MAP       10340          3 BUILD_TUPLE     28527          6 <46>                     7 DELETE_GLOBAL   29281 (29281)         10 STORE_SLICE+1         11 SLICE+2         12 DELETE_SUBSCR           13 DELETE_SUBSCR           14 SLICE+2          15 BUILD_MAP       10340         18 PRINT_EXPR              19 JUMP_IF_FALSE_OR_POP 11887         22 DELETE_GLOBAL   29281 (29281)         25 STORE_SLICE+1In [8]: dis.dis("foo.bar is Foo.bar")          0 BUILD_TUPLE     28527          3 <46>                     4 DELETE_GLOBAL   29281 (29281)          7 SLICE+2          8 BUILD_MAP        8307         11 PRINT_EXPR              12 JUMP_IF_FALSE_OR_POP 11887         15 DELETE_GLOBAL   29281 (29281)

The real situation is when executing the. operator when the actual is generated a proxy object, Foo.bar is Foo.bar time, two object order generation, placed in the stack compared, because the address is different is certainly false, but the ID (foo.bar) = = ID (foo.bar) The time is different, first generate Foo.bar, and then calculate the address of foo.bar, after calculating the foo.bar address, there is no object to Foo.bar, so the Foo.bar object will be released. The Foo.bar object is then generated, because the memory size used by Foo.bar and Foo.bar is the same, so the memory address of the original foo.bar is reused, so the result of the ID (foo.bar) = = ID (foo.bar) is true.

The following content is provided by mail Leo Jay Daniel, who explains the more transparent.

It is problematic to use the ID (expression a) = = ID (expression b) to determine that the result of two expressions is not the same object.

Foo.bar This form is called attribute reference [1], which is one of the expressions. Foo is a instance Object,bar is a method, and this time the expression foo.bar returns the result called Method Object [2]. According to the documentation:

When an instance attribute was referenced that isn ' t a data attribute, it class is searched.  If the name denotes a valid class attribute a function object, a method object is created by packing (pointers to) The instance object and the function object just found together in a abstract Object:this is the method object.

Foo.bar itself is not a simple name, but the expression of the result, is a method object, in the ID (foo.bar) Such an expression, method object is only a temporary intermediate variable, do not have the meaning of the temporary intermediate variable ID.

A more obvious example is that

1 printid(foo.bar) ==id(foo.__init__)

The result of the output is also true

Look at the ID of the document [3]:

Return the "Identity" of an object. The is a integer (or long Integer) which is guaranteed to being unique and constant for the this object during its lifetime. The same ID () value is objects with non-overlapping lifetimes. CPython implementation Detail:this is the address of the object in memory.

Only if you can guarantee that the object will not be destroyed, you can compare two objects with an ID. So, if you have to be more than that, you have to write:

123 fb =foo.bar Fb = Foo.bar print id(fb) ==id(Fb)

You can get the correct result by binding the result of two expressions to the name and then to the same object.

The IS expression [4] is also the same, you now get the correct result, completely because the implementation details of the CPython now decided. The current is implementation, is the left and right sides of the object are calculated, and then compare the two objects are the same address. In case one day change to, first count left, save the address, left off, then the right side, then compare, your is the result may be wrong. [5] The issue is also mentioned in the official documentation. I think the right way is also like ID, first the left and right sides are computed, and explicitly bound to their names, and then use is to judge.

[1] Http://docs.python.org/2/reference/expressions.html#attribute-references
[2] Http://docs.python.org/2/tutorial/classes.html#method-objects
[3] Http://docs.python.org/2/library/functions.html#id
[4] http://docs.python.org/2/reference/expressions.html#index-68
[5] Http://docs.python.org/2/reference/expressions.html#id26

Is and ID in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.