Python FAQ: integer comparison

Source: Internet
Author: User
Tags class definition

In Python everything is an object, without exception an integer is also an object, the comparison between objects can be used = =, can also use is. The difference between = = and is operation is:

Is compares the ID values of two objects for equality, that is, whether the two objects are the same instance object, or if they point to the same memory address. = = Compares the contents of two objects for equality, by default calling the object's __eq__ () method.

After you know the difference between IS and = =, perhaps you may encounter the following confusion, so there is an article, trying to get some of Python's vague things out of the hope that you have some help. Let's look at two pieces of code first:

Fragment One:

>>> A = $ >>> b = $-A = = = B True >>>

Fragment Two:

>>> a = >>> B = +/-A is B True >>>

In the interactive command line execution of the above two pieces of code, the code fragment one of the A==b returns true is very well understood, because the value of two objects is 256, for fragment two, A is B also returns true, which shows that A and B are pointing to the same object, you can check their ID values are equal:

>>> ID (a) 8213296 >>> ID (b) 8213296 >>>

The result is that they are indeed the same object, pointing to the same memory address. That's not all integer objects. As long as the values (contents) of two objects are equal, are they the same instance object? In other words, for an integer object as long as = = Returns the True,is operation also returns true? Take this question to see the following two pieces of code:

Fragment One:

>>> a = 257 >>> b = 257 >>> A = = B True >>>

Fragment Two:

>>> a = 257 >>> b = 257 >>> A is b False >>yszx11.cn >

For 257,a is B to return is false, the results may be expected in you, but also may be unexpected to you, but anyway, we have to find out the truth of the problem.

Doubts one

For performance reasons, Python has done a lot of optimization work, and for integer objects, Python caches a number of frequently used integer objects and saves them to a linked list called small_ints, where any reference to these integer objects is required throughout the life of Python. No longer re-creates the new object, but instead directly references the object in the cache. Python places the small objects in the range [-5, 256] that are likely to be used frequently in the small_ints, but when you need to use little integers, take them from there and no longer create new objects temporarily. Because 257 is no longer in the range of small integers, so although the values of A and B are the same, they exist within Python as two separate objects, fragmented and non-intrusive.

After figuring out the first question, we continue to write a function in the Python interactive command line, and then look at the following code:

Fragment One:

>>> C = 257 >>> def foo (): ... a = 257 ... b = 257 ... print a is b ... print a is c ... >> > foo () True False

Well, what's the case, yes, you're not mistaken, in the case where the code A and B values are 257, A is B returns true, and A is C returns a value of False,a, B, and C as 257, why do different results occur? Is this a complete denial of what has happened in this code? Is it wrong to conclude that the doubts are correct?

Two doubts

A Python Program was constructed from code blocks. A block is a piece of the Python program text, which is executed as a unit. The following is BLOCKS:A module, a function body, and a class definition. Command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the Interprete R) is a code block. A script command (a command specified on the interpreter command line with the '-C ' option) is a code block. Structure-of-a-program zhengshu5.com

In order to understand this problem, it is necessary to comprehend the concept of program code block first. Python programs consist of blocks of code, which are executed as a minimal basic unit of the program. A module file, a function body, a class, and a single line of code in an interactive command are called a block of code. In the above code, consisting of two blocks of code, C = 257 as a block of code, and function Foo as another block of code. Inside Python in order to further improve performance, any integer object created in a block of code, if there is a value with the same object in the code block, then directly reference, otherwise create a new object out. Python is based on performance considerations, but for non-mutable objects, objects in the same code block, only objects of the same value, are not created repeatedly, but directly refer to objects that already exist. Therefore, not only the integer object, but also the string object follows the same principle. So A is B takes for granted the return to true, and C and a are not in the same block of code, so two objects inside Python are created with 257 values. In order to verify the conclusion, we can borrow the dis module from the point of view of bytecode to see this code.

>>> import dis  >>> dis.dis (foo)     2            0 LOAD_CONST                1  (257)                  3 STORE_FAST                0  (a)         3           6 LOAD_CONST                1  (257)                  9 STORE_FAST                1  (b)         4          12 LOAD_FAST                 0  (a)                 15 LOAD_FAST                 1  (b)                 18 COMPARE_OP                8  (IS)                 21 PRINT_ITEM                          22 print_ newline             5           23 load_fast                 0  (a)                 26 load_global              0   (c)                29  compare_op               8  (IS )                32 print_item                           33 PRINT_NEWLINE                      34 LOAD_CONST                0  (None)                 37 RETURN_VALUE  

You can see that two of the 257 are obtained from the same position in the constant pool co_consts[1].

Summarize

After a lengthy lecture, two points were reached: 1, small integer Object [-5,256] is reused within the scope of the global interpreter and will never be recycled by GC. 2. Immutable objects in the same block of code will not create new objects repeatedly as long as the values are equal. It seems that these points of knowledge are not helpful to the daily work, because you do not use is to compare the values of two integer objects for equality. Then why do we have to talk about it? Well, programmers learn knowledge, should not be tasted, to give full play to the spirit of death.

Python FAQ: integer comparison

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.