Skip to content

Question 27

What is the output of the following code?

class Item():
    def __init__(self, name, price, qty):
        self.name = name
        self.price = price
        self.qty = qty
        self.revenue = 0

    def discount(self, discount):
        if discount < self.price:
            self.price -= discount

    def buy(self):
        if self.qty > 0:
            self.qty -= 1
            self.revenue += self.price

labubu = Item('labubu', 300, 3)
labubu.discount(100)
labubu.buy()
labubu.discount(250)
labubu.buy()
labubu.discount(50)
labubu.buy()
labubu.buy()
print(labubu.revenue)
Hint

The Item class contains 3 class members. Form their respective values with the parameters passed into the constructor. Then, follow along with the called methods in subsequent method calls.

Solution

labubu is initialized as an object of class Item with the following class members:

  • self.name: name = 'labubu'
  • self.price: price = 300
  • self.qty: qty = 3
  • self.revenue: 0

Let's now work through the rest of the subsequent statements.

  • labubu.discount(100):
    • Since 100 is less than labubu.price = 300, labubu.price is now 300 - 100 = 200.
  • labubu.buy():
    • Since labubu.qty = 3 > 0, decrement labubu.qty to 2. Then, increment labubu.revenue by the value of labubu.price, i.e., 0 + 200 = 200.
  • labubu.discount(250):
    • Since 250 is more than labubu.price = 200, labubu.price remains unchanged at 200.
  • labubu.buy():
    • Since labubu.qty = 2 > 0, decrement labubu.qty to 1. Then, increment labubu.revenue by the value of labubu.price, i.e., 200 + 200 = 400.
  • labubu.discount(50):
    • Since 50 is less than labubu.price = 200, labubu.price is now 200 - 50 = 150.
  • labubu.buy():
    • Since labubu.qty = 1 > 0, decrement labubu.qty to 0. Then, increment labubu.revenue by the value of labubu.price, i.e., 400 + 150 = 550.
  • labubu.buy():
    • Since labubu.qty = 0, do nothing. labubu.revenue remains at 550.

print(labubu.revenue) now prints 550.

Answer
550