In CPython -
the 10 + 20 in Python source code is encoded in the AST to two int object with value 2 and the Binary operation’+’
This AST is compiled to The Byte codes to load the object reference onto the stack and the byte code to execute the Binary Operation. This stream of Byte codes is passed to the virtual machine.
The virtual machine will push the two integer objects to the calculations stack and then call the __add__ method of the integer 2 object (or its equivalent since integers are builtin).
The code for the __add__ method will extract the internal C longInt value for both operands and calculate the result.
As part of a memory optimization for small ints, it then identifies that there is a Python int object already in existence with the value of 4, and since Python integers are immutable there is no problem using that Integer 4 object again.
finally, It arranges for the Python integer 4 objects to be returned from the __add__ method of high results in the 4 object reference being pushed onto the calculation stack.
Post a Comment