Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 cookies inside the jar):

class Jar:
    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 Cookies") 
        if self.size > self.capacity:
            raise ValueError("OverCapacity")   
        self._size = size     

def main():
    jar=Jar()
    jar.deposit(12)
    jar.withdraw(14)
    print(jar)

if __name__ == "__main__":
    main()

I expected that this would return a value error of insufficient cookies 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading