user1030312
user1030312

Reputation:

Modifying a numpy array in-place or how to get a reference to a numpy array to be updated

I have a Data class with one field, price. I referenced the price field in another class Store. How should it be done so that Store see modification made to price? Here is the situation in code.

import numpy as np

class Data:
    def __init__(self):
        self.price=np.array([1,2,3])

    def increasePrice(self,increase):
        self.price=self.price*increase

class Store:
    def __init__(self):
        self.data=Data()
        self.price=self.data.price

    def updateData(self):
        self.data.increasePrice(2)
        print self.data.price #print [2,3,6]
        print self.price      #print [1,2,3]

The only way I find to do it is to re-referenced price.

class Store:
    ....
    def updateData(self):
        self.data.increasePrice(2)
        self.price=self.data.price #re-referencing price
        print self.data.price #print [2,3,6]
        print self.price      #print [2,3,6]

But I would like a more 'automatic' way to keep the fields sync. I'm new to python and I'm not clear on the scoping rules. Thanks for any help.

Upvotes: 0

Views: 113

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601529

The easiest solution of this problem is not to replicate price in Store instances -- simply use self.data.price everywhere.

If this is not an option for some reason, you can define a property:

class Store(object):
    ...
    @property
    def price(self):
        return self.data.price

This way, the data property of Store instances will always return the current value of self.data.price.

Upvotes: 2

Related Questions