2012-03-24 3 views
0

하나의 필드에 price라는 데이터 클래스가 있습니다. 다른 클래스 저장소에서 가격 필드를 참조했습니다. 스토어에서 수정 된 가격을 확인하려면 어떻게해야합니까? 다음은 코드의 상황입니다.numpy 배열을 수정하거나 numpy 배열을 업데이트 할 수있는 방법을 수정하는 방법

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] 

내가 할 수있는 유일한 방법은 가격을 다시 참조하는 것입니다.

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] 

하지만 필자는 필드 동기화를 유지하는 '자동'방법을 원합니다. 저는 파이썬을 처음 접했고 범위 지정 규칙에 대해 명확하지 않습니다. 도움 주셔서 감사합니다.

답변

2

priceStore 인스턴스에 복제하는 것이 가장 쉬운 방법입니다. self.data.price을 어디서나 사용하십시오.

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

이 방법은, Store 인스턴스의 data 속성은 항상 self.data.price의 현재 값을 반환합니다 :이 어떤 이유에 대한 옵션이없는 경우

, 당신은 속성을 정의 할 수 있습니다.

+0

감사합니다. 매우 명확한 답변입니다. –

관련 문제