2016-11-30 61 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