John Walker
John Walker

Reputation: 53

Class and objects in Python

I'm running a simple online shopping cart program and when I tried to run it, the ending result was blank. I understand the concept about classes and objects, but I really need assistance. It is supposed to look like this:

Item 1
Enter the item name: Chocolate Chips
Enter the item price: 3
Enter the item quantity: 1

Item 2
Enter the item name: Bottled Water
Enter the item price: 1
Enter the item quantity: 10

TOTAL COST
Chocolate Chips 1 @ $3 = $3
Bottled Water 10 @ $1 = $10

Total: $13

Here's what I've written so far, :

class ItemsToPurchase :

    def __init__(self, item_name = "none", item_price = 0, item_quantity = 0):
        self.item_name = item_name
        self.item_price = item_price
        self.item_quantity = item_quantity

    def print_item_cost(self):
        total = item_quantity * item_price
        print('%s %d @ $%f = $%f' % (item_name, item_quantity, item_price, total))

def main():

    print('Item 1')
    print()

    item_name = str(input('Enter the item name: '))
    item_price = float(input('Enter the item price: '))
    item_quantity = int(input('Enter the item quantity: '))

    item_one = ItemsToPurchase(item_name, item_price, item_quantity)
    item_one.print_item_cost()

    print('Item 2')
    print()

    item_name = str(input('Enter the item name: '))
    item_price = float(input('Enter the item price: '))
    item_quantity = int(input('Enter the item quantity: '))

    item_two = ItemsToPurchase(item_name, item_price, item_quantity)
    item_two.print_item_cost()

    print('TOTAL COST')
    item_one.print_item_cost()
    item_two.print_item_cost()

if __name__ == "__main__":
    main() 

What did I do wrong?

Upvotes: 0

Views: 899

Answers (1)

Jarvis
Jarvis

Reputation: 8564

You have some issues in your print_item_cost method, it should be like this :

def print_item_cost(self):
    total = self.item_quantity * self.item_price
    print('%s %d @ $%f = $%f' % (self.item_name, self.item_quantity, self.item_price, total))

You refer to a class attribute like this : self.attr

Upvotes: 3

Related Questions