如何通过引用更改类属性?

时间:2018-07-07 01:04:40

标签: python class

class Stock:
  def __init__(self,
               stock = 'GOOG',
               period = '1Y',
               interval = 86400,
               market = 'NASDAQ'):

    self.stock = stock
    self.period = period
    self.inteval = interval
    self.market = market

    data = get_price_data({'q': stock, 'p': period, 'i': interval, 'x': market})
    self.data = data

MU = Stock('MU')

我希望能够更新属性,例如MU.period = '14d',并自动重新计算数据。

我尝试做类似的事情

   @period.setter
    def period(self, val):
        self._period = val
        self.data = data(self.stock, self.period, self.interval, self.market)

但它抛出了错误'str' object has no attribute 'setter'

1 个答案:

答案 0 :(得分:2)

仅当您已经将@period.setter声明为property时,才能完成period

您还将需要一个吸气剂-通常只需使用开头的@property进行声明即可。

最后,您可能想转到period属性后面,然后将内容直接存储在_period的raw __init__属性中,因为否则,您将不得不设置{ {1}}两次。

所以:

self.data

您可能还希望将class Stock: def __init__(self, stock = 'GOOG', period = '1Y', interval = 86400, market = 'NASDAQ'): self.stock = stock self._period = period self.inteval = interval self.market = market data = get_price_data({'q': stock, 'p': period, 'i': interval, 'x': market}) self.data = data @property def period(self): return self._period @period.setter def period(self, val): self._period = val self.data = data(self.stock, self.period, self.interval, self.market) 设为只读的data,以确保没有人不小心将其破坏,但这可能不值得(“同意成人”等等。