tieguanyin
tieguanyin

Reputation: 321

Changing a variable within a class causes global variables to change as well?

Here is the code:

import numpy as np

weights = np.array([[2.,3.,4.],[5.,6.,7.,]])

class TTESt:

    def __init__(self,weight_new):
        self.weight_new = weight_new

    def changeweights(self):

        temp = np.zeros(shape = (2,3))
        temp_weights = self.weight_new
        temp_weights[0,0] = 1000.

        return temp_weights

aaa = TTESt(weights)
aaa.changeweights()
print(weights)

I expected the output of print(weights) to be np.array([[2.,3.,4.],[5.,6.,7.,]]) (remains itself).

But it is not.

The output of this code is:

[[1000.    3.    4.]
 [   5.    6.    7.]]
[[1000.    3.    4.]
 [   5.    6.    7.]]

Why the global variable weights changes? I did not assign a new value to it.

What could I do to avoid this problem from coming up again?

Thank you!

Upvotes: 0

Views: 37

Answers (1)

brentertainer
brentertainer

Reputation: 2188

In Python, there is no concept of "pass by reference" or "pass by value". Everything is "pass by name". That said, there is a difference between passing mutable and immutable objects.

You are passing the global weights, a mutable object, to the class constructor. Since it's mutable, it's sort of analogous to passing by reference. The scope in which you modify the object does not matter. Whether you use the name in the scope of the class (self.weights_new) or the name in the global scope (weights), the object is the same.

If you instead pass and modify an immutable object like a tuple, it will behave more like "pass by value".

Upvotes: 2

Related Questions