Search code examples
python-3.xclass-method

How to increase instance variable in class method in Python


I am stuck in this question (part two). The question is as follows: Create a class called AppleBasket who's constructor accepts two inputs: a string representing a color, and a number representing a quantity of apples. The constructor should initialize two instance variables: apple_color and apple_quantity. Write a class method called increase that increases the quantity by 1 each time it is invoked. You should also write a str method for this class that returns a string of the format: "A basket of [quantity goes here] [color goes here] apples." e.g. "A basket of 4 red apples." or "A basket of 50 blue apples."

My code is:

class AppleBasket():
    def __init__(self, apple_color, apple_quantity):
        self.apple_color = apple_color
        self.apple_quantity = apple_quantity

    def getC(self):
        return self.apple_color

    def getQ(self):
        return self.apple_quantity

    def __str__(self):
        return "A basket of {} {} apples.".format(self.apple_quantity, self.apple_color)

    def increase(self):
        return self.apple_quantity + 1


print(AppleBasket("Red", 4))

However, Quantity still remains at 4 instead of 5.

Can some please advice me what mistake am I doing? Thank you.


Solution

  • correct your increase method:

        def increase(self):
            self.apple_quantity += 1