[Python] Looping through object instance variables does not change value

Discussão em 'Python' iniciado por Stack, Novembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    I have a class that contains two object instance variables.

    import numpy as np
    class test(object):
    def __init__(self):
    self.a=np.array((1,2))
    self.b=np.array((1,2))


    I need a method that does similar operations to each variable. I thought that I could loop over the variable and it would change the values in place. However, when i execute the numpy insert and assign the value to a, it does not change self.a.

    def indirect_method(self):
    arrs = [self.a, self.b]
    for a in arrs:
    a = np.insert(l,1,3)
    t=test()

    t.indirect_method()

    t.a
    Out[82]: array([1, 2])

    t.b
    Out[83]: array([1, 2])


    If I print the ID of self.a and a, initially they are the same, but after the insert operation the ID of a changes.

    def indirect_method(self):
    arrs = [self.a,]
    print(id(self.a))
    for a in arrs:
    print(id(a))
    a = np.insert(l,1,3)
    print(id(a))


    t=test()

    t.indirect_method()

    4756930896
    4756930896
    4744668432


    If I modify the object variables directly it works fine.

    def direct_method(self):
    self.a = np.insert(self.a,1,3)
    self.b = np.insert(self.b,1,3)

    t=test()

    t.direct_method()

    t.a
    Out[77]: array([1, 3, 2])

    t.b
    Out[78]: array([1, 3, 2])


    How can I update self.a and self.b through an intermediary variable? This would save a lot of duplicated code since the only part of my method that needs to change is the location where the data is inserted.

    Continue reading...

Compartilhe esta Página