1
class Item:
    pay_rate = 0.8 # The pay rate after 20% discount
    all = []
    def __init__(self, name: str, price: float, quantity=0):
        # Run validations to the received arguments
        assert price >= 0, f"Price {price} is not greater than or equal to zero!"
        assert quantity >= 0, f"Quantity {quantity} is not greater or equal to zero!"

        # Assign to self object
        self.name = name
        self.price = price
        self.quantity = quantity

        # Actions to execute
        Item.all.append(self)

    def calculate_total_price(self):
        return self.price * self.quantity

    def apply_discount(self):
        self.price = self.price * self.pay_rate

    def __repr__(self):
        return f"Item('{self.name}', {self.price}, {self.quantity})"

item1 = Item("Phone", 100, 1)
item2 = Item("Laptop", 1000, 3)
item3 = Item("Cable", 10, 5)
item4 = Item("Mouse", 50, 5)
item5 = Item("Keyboard", 75, 5)

print(Item.all)

I know that the magic method __repr__ is allowing each item in the all list to be displayed. But unlike the other methods, why is it never called?

If I wanted to use the calculate_total_price method, id do print(item1.calculate_total_price). But do the the __repr__ I use Item.all ?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
kbleu5
  • 11
  • 1
  • "why is it never called" - it *is* called. Just not by code you wrote. – user2357112 Mar 26 '23 at 02:49
  • Welcome to Stack Overflow. `__repr__` tells Python how to print an instance of the class. The code says to print `Item.all`, which is a list that contains instances of the class. Python knows how to print lists: basically it outputs `[`, then each element separated by `,`, then `]`. The only missing piece of the puzzle is how to print the elements. But since these elements are instances of the class, and it's known how to output instances of the class, there is no problem. Please see the linked duplicate for details. – Karl Knechtel Mar 26 '23 at 02:51
  • `Item.all` is a list. `print(Item.all)` calls `list._str__`. This method is implemented to call the `__repr__` for each of its items. When you run your code, you see `[Item('Phone', 100, 1),...]`, - that's your `__repr__` being called for each list value. BTW, please add the output to your question. Its an important detail. – tdelaney Mar 26 '23 at 02:56

0 Answers0