2016-11-30 65 views
0

我正在運行一個簡單的在線購物車程序,當我試圖運行它時,最終結果爲空。我理解關於類和對象的概念,但我真的需要幫助。它應該是這樣的:Python中的類和對象

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 

這裏是我到目前爲止寫的,:

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() 

我做了什麼錯?

+0

不知道這僅僅是你問的問題但是,對main()的調用不會在if語句 – Sighonide

+0

下縮進。您得到的錯誤是什麼? – Prajwal

+0

這是在一個單獨的過程中運行嗎? – Sighonide

回答

3

您的print_item_cost方法有些問題,它應該是這樣的:

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)) 

你指的是類屬性是這樣的:如果self.attr

+0

如果上面已經解決了這個問題,忽略這個:假設你在一個子進程中運行這個函數(假設這是使用:if __name__ ==「__main __」:'),那麼你可能需要刷新sys。通過在上面的代碼中調用'sys.stdout.flush()'(在調用所有的打印函數之後)調用stdout'。這是由於被緩衝的子進程的輸出。 如果你沒有使用多個進程,請忽略這個 – Sighonide

+0

據我所知,沒有提及多重編程,據我所知使用'__name__ ==「main」'是常見的事情。 OP的代碼還有其他問題。你可以看到我的答案,併爲自己檢查。 (並希望太快:))@Sighonide – Jarvis

+1

我同意你的回答:)我只覆蓋所有的基礎,因爲'__name__ ==「main」'可能會提示多處理。但現在我想到了,他可能只是想能夠在不運行main()的情況下導入類和函數定義,並且能夠從頭開始運行它:/ lol – Sighonide