0

I've created a simple class with object that has init value x0. When I change another value x, my x0 is also changing.

I thought that x0 should remain unchanged. Could you please explain why is this happening?

file main.py:

import numpy as np
from simpleclass import test


def main():

    params = dict()
    params['position'] = np.array([1.0, 2.0])

    object = test(params)

    print(object.x0)
    print(object.x)

    object.run(2)

    print(object.x0)
    print(object.x)


if __name__ == "__main__":
    main()

file simpleclass.py:

class test():

    def __init__(self, params):
        self.x0 = params['position']
        self.x = self.x0

    def run(self, num):
        self.x += self.x*num

result:

[ 1.  2.]
[ 1.  2.]
[ 3.  6.]
[ 3.  6.]
Arun
  • 1,933
  • 2
  • 28
  • 46
Gatto Nou
  • 89
  • 1
  • 12

3 Answers3

3

problem is with

class test():
    def __init__(self, params):
        self.x0 = params['position']
        self.x = self.x0

    def run(self, num):
        self.x += self.x*num

self.x = self.x0 here self.x and self.x0 are pointing same object. you can make copy of self.x0.

import copy

class test():
    def __init__(self, params):
        self.x0 = params['position']
        self.x = copy.deepcopy(self.x0)

    def run(self, num):
        self.x += self.x*num
surya singh
  • 450
  • 2
  • 12
1

surya singh is right, just print the memory address, you will get the same numbers

class test():
    def __init__(self, params):
        self.x0 = params['position']
        self.x = self.x0
        print id(self.x)
        print id(self.x0)
Jiri Semmler
  • 411
  • 3
  • 11
1

You are only passing a reference

By self.x = self.x0, you are only passing a reference. With self.x += self.x*num, the reference is unchanged too. So after those two operations, x and x0 still points to the same array.

It would be different if you used an immutable object, such as tuple

params['position'] = (1, 2)

With tuple, += does something different than what you want, but you see, x and x0 points to different object.

(1, 2)
(1, 2)
(1, 2)
(1, 2, 1, 2, 1, 2)

Use a copy

You want to create a copy of your array, numpy has a built-in method for that

self.x = self.x0.copy()

Result:

[ 1.  2.]
[ 1.  2.]
[ 1.  2.]
[ 3.  6.]
pacholik
  • 8,607
  • 9
  • 43
  • 55