我有一堂简单的课。我想使用专用属性设置periodicity
属性,该属性在用于设置公共属性之前已经过测试。我在类模块周围传递了self,当我运行测试代码时,该函数似乎需要2个参数。我认为它应该忽略self
并要求一个freq
参数。我正在尝试成为“ pythonic”,并将@property
与.setter
一起使用。我需要更改属性调用吗?如果我从self
中删除了set_periodicity
,它说它不能识别self
。
class ModelSetUp:
def __init__(self):
self.periodicity= None
@property
def set_periodicity(self,freq):
self.periodicity = self._periodicity
@set_periodicity.setter
def set_periodicity(self,freq):
if freq in ("Q","S","A"):
self._periodicity = freq
else:
raise ValueError("Frequency Must Be Q, S or A")
if __name__=="__main__":
mod = ModelSetUp()
mod.set_periodicity("Q")
答案 0 :(得分:2)
属性不接受任何参数,也不可调用。试试这个:
class ModelSetUp:
def __init__(self):
self._periodicity = None
@property
def periodicity(self):
return self._periodicity
@periodicity.setter
def periodicity(self, freq):
if freq in ("Q","S","A"):
self._periodicity = freq
else:
raise ValueError("Frequency Must Be Q, S or A")
if __name__=="__main__":
mod = ModelSetUp()
mod.periodicity = "Q"