为什么我在此类中遇到“缺少1个位置参数”错误?

时间:2019-09-18 14:48:16

标签: python class properties

我有一堂简单的课。我想使用专用属性设置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")




1 个答案:

答案 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"