Does importing a variable from a module in python make a copy?

It seems to be from foo import imaking a copy of i, rather than importing me into the current namespace. Is it possible?

foo.py:

i=0

bar.py:

import foo
from foo import i

foo.i = 999

print i
print foo.i

Fingerprints:

0
999

but I expected them both to be 999 (just aliases for the same memory). What am I missing?

+1
source share
1 answer

just aliases for the same memory

You misunderstood how β€œvariables” work in python. Variables - this cell is not . These are just names attached to objects. When you do the assignment:

i = 0

you specify a name for the inew object 0in the current area.

You should read the naming and binding documentation.


, :

i:

foo.i       i
  |        /
  |       /
  |      /
  |     /
  |    /
  |   /
  |  /
+-----+
| 999 |
+-----+

999 . :

i = 0

:

foo.i         i
  |           |
  |           |
  |           |
  |           |
  |           |
  |           |
  |           |
+-----+     +---+
| 999 |     | 0 |
+-----+     +---+

999... : , python .

, :

i = 999
j = i
i = 0
print(i, j)  # prints: 0 999

i j - . C, python . :

int *i = &999;
int *j = i;
i = &0;
printf("%d %d", *i, *j);
+5

All Articles