Understanding python name binding

I am trying to clarify for myself the Python rules for assigning values ​​to variables.

Is the following comparison between Python and C ++ valid?

  • In C / C ++, a statement int a=7means that memory is allocated for an integer variable with a name a(number on the LEFT character =) and only then the value 7 is stored in it.

  • In Python, a statement a=7means that first an unnamed integer object is created with a value of 7 (the number is on the RIGHT side =) and stored somewhere in memory. Then the name is abound to this object.

The output of the following C ++ and Python programs seems to confirm this, but I would like to get some feedback on whether I am right.

C ++ creates different memory cells for aand b while, aand bit seems, refer to the same place in Python (go to the output of the id () function)

C ++ code

#include<iostream>
using namespace std;
int main(void)
{
  int a = 7;
  int b = a; 
  cout << &a <<  "  " << &b << endl; // a and b point to different locations in memory
  return 0;
}

Output: 0x7ffff843ecb8 0x7ffff843ecbc

Python: code

a = 7
b = a
print id(a), ' ' , id(b) # a and b seem to refer to the same location

Output: 23093448 23093448

+4
source share
2 answers

Yes, you are basically right. In Python, a variable name can be thought of as a reference to a value (not in terms of a C ++ reference, although this works similarly, more simply declaring that it refers to something).

As an aside, the Python method is very similar to C ++ int &b = a, which simply means that ait brefers to the same value.

C int *pb = &a, , a *pb , , , C: -)

Python , , :

a = 7   # Create "7", make "a" refer to it.
b = a   # make "b" refer to  the "7" as well.
a = 42  # Create "42", make "a" refer to it, b still refers to the "7".

( "create", - -, ).

C- b = a , "7" b. Python a b, .

( ), Python , , C.

, ( , C ++), , , :

>>> a = [1,2,3] ; print a
[1, 2, 3]

>>> b = a ; print b
[1, 2, 3]

>>> a[1] = 42 ; print a
[1, 42, 3]

>>> print b   #WTH?
[1, 42, 3]

, :

b = a[:]
b = [item for item in a]

( , b = a ) deepcopy, , , .

+5

, "int" ++, "=" , "=" , . python Java, , .

:

a = 7
b = 7
print id(a), ' ' , id(b) 

, python a, b

0

All Articles