简体   繁体   English

在 python 中定义 class 属性时出现问题

[英]problem defining class property in python

I'm new to python programming, I'm trying to encapsulate all property checking of a size in the class object below but one of them is not working (checking to see if withdraw is bigger than amount of books inside the shelf):我是 python 编程的新手,我试图将所有属性检查封装在下面的 class object 中,但其中一个不起作用(检查撤回是否大于书架内的书籍数量):

class Shelf:
    def __init__(self, capacity=12):
        self.capacity = capacity
        self._size = 0        

    def __str__(self):
        return("📕" * self.size)

    def deposit(self, n):
        self.size = n + self.size

    def withdraw(self, n):
        self.size = self.size - n
        print(self.size)

    @property
    def capacity(self):
        return self._capacity

    @capacity.setter
    def capacity(self, capacity):
        if capacity < 0:
            raise ValueError("None Positive Capacity")
        self._capacity = capacity

    @property
    def size(self):
        return self._size

    @size.setter
    def size(self, size):
        print(self.size)
        if self.size < 0:
            raise ValueError("Insufficient books") 
        if self.size > self.capacity:
            raise ValueError("OverCapacity")   
        self._size = size     

def main():
    shelf=Shelf()
    shelf.deposit(12)
    shelf.withdraw(14)
    print(shelf)

if __name__ == "__main__":
    main()

I expected that this would return a value error of insufficient books but it doesn't.我预计这会返回书本不足的值错误,但事实并非如此。 I've added print to the code to see the behavior.我已将 print 添加到代码中以查看行为。 I've noticed that the withdraw method works but the resulting value isn't checked by the size property setter.我注意到 withdraw 方法有效,但结果值未由 size 属性设置器检查。

You must use it like this, because the argument you give (size) is -14 and self.size is 0. You should check size Instead self.size.你必须这样使用它,因为你给的参数 (size) 是 -14 而 self.size 是 0。你应该检查 size 而不是 self.size。

   def size(self, size):
        if size < 0:
            raise ValueError("Insufficient Cookies")
        if size > self.capacity:
            raise ValueError("OverCapacity")
        self._size = size

Do not forget to change the capacity value when increasing or decreasing the size.增加或减小大小时不要忘记更改容量值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM