problem defining class property in python

Question:

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):

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. I’ve noticed that the withdraw method works but the resulting value isn’t checked by the size property setter.

Asked By: Alireza Taheri

||

Answers:

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.

   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.

Answered By: Ali Dehkhodaei