0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments