-1

I have the sample code below:

A = None       
class App(object):
    def __init__(self, a):
        global A
        A = a   
a = {'x': 1}
print(A)  # None

App(a)
print(A)  # {'x': 1}

a['x'] = 2
print(A)  # {'x': 2} # value change if dictionary

a = 2
print(A)  # {'x': 2} # value not change

But I don't know why global A has been change value? Help me know this please

Duc Tran
  • 115
  • 1
  • 3
  • 8
  • 1
    Just as saying `print(a)` prints the object itself instead of printing the string `a`, `A = a` assigns `A` to the object itself, not the the name `a`. `A` is the same as `a` just because they refer to the same object. When you use `a['x'] = 2`, you are doing an operation on the object. Since `A` refers to the same object, the changes are visible when you print `A`. When you say `a = 2`, `a` now refers to a different object. It is not modifying the object that it used to refer to, so the changes are not visible in `A`. – zondo Mar 30 '16 at 02:47
  • @zondo nice, I think here is the answer what I need – Duc Tran Mar 30 '16 at 02:51

1 Answers1

0

You are using the line global A in your class method. This makes sure that the variable A referred there is the same as the global A you define in the first line. If you were to leave out that statement, a new local variable A would have been defined in the function.

Once you run the class method, A now references a. So all changes to a apply to A as well.

In the very last line you change the type of the variable a and it's value. A will now lose its binding to a. See this answer for the explanation: "if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object."

Community
  • 1
  • 1
roadrunner66
  • 7,772
  • 4
  • 32
  • 38
  • I deliberately use global variable. I just do not understand why re-assign "a" dictionary to alter the "A" – Duc Tran Mar 30 '16 at 02:43