如何在子类上添加只读属性? Python 3

时间:2020-08-28 21:32:52

标签: python python-3.x inheritance properties

我不知道该怎么做...“计数”它被认为是只读属性,我不确定在Inherence上实现该方法的方式,(我不知道确切的方法是原来的班级COZ是班级练习)

我希望有人可以帮助我...我在这里放代码

class SteppedCounter(Counter):
    def __init__(self, count, step):
        super.__init__(count)
        self.__step = step
        
    @property
    def step(self):
        return self.__step


if __name__ == "__main__":
    # Example of use (not part of the solution)
    c = SteppedCounter(3)
    print(c.count)
    print(c.step)
    c.add_up()
    print(c.count)

这是我在__init__中放入计数时的错误消息

TypeError: __ init__() missing 1 required positional argument: 'step' 

当我不这样做时:

'SteppedCounter' object has no attribute '_Counter__count' 

如果我在c = SteppedCounter(3)中添加一个数字,就像c = SteppedCounter(1, 3),则显示以下消息:

TypeError: descriptor '__init__' requires a 'super' object but received a 'int'

1 个答案:

答案 0 :(得分:0)

您应该在super()调用中添加括号:

super().__init__(count)

您绝对应该为构造函数提供指定数量的参数(本例中为2)。

相关问题