[英]How can I add the attributes of 2 classes using method overloading?
1.我真的有兩個問題。 首先,我得到了意想不到的輸出
None None
從我的最后一行代碼
我對第二個項目重復此操作,然后我想顯示這兩個項目,並顯示單獨的總計以及合並的總計。 它應該是這樣的
TOTAL COST
Apple 3 @ $2 = $6
Balls 4 @ $4 = $16
Total: $22
我得到了這個
TOTAL COST
x 3 @ $2 = $6
y 6 @ $4 = $24
None None
我不知道“無無”從何而來,也不知道如何在不刪除項目信息的情況下將其刪除,而且我不知道如何使用重載來合並成本。 我的代碼在這里的add方法中有一個解決方案
class Item:
def __init__(self, name = 'none', price = 0, quantity = 0):
self.item_name = name
self.item_price = price
self.item_quantity = quantity
self.total = price * quantity
def __add__(self, other):
return self.total + other.total
def print_item_cost(self):
return print('{} {} @ ${} = ${}'.format(self.item_name,
self.item_price,
self.item_quantity,
self.total))
#Grab first item
print('Item 1')
name_1 = input('Enter the item name: ')
price_1 = int(input('Enter the item price: '))
qty_1 = int(input('Enter the item quantity: '))
item_1 = Item(name_1, price_1, qty_1)
#Grab second item
print('\nItem 2')
name_2 = input('Enter the item name: ')
price_2 = int(input('Enter the item price: '))
qty_2 = int(input('Enter the item quantity: '))
item_2 = Item(name_2, price_2, qty_2)
#Output cost
print('\n\nTOTAL COST')
print(item_1.print_item_cost(), item_2.print_item_cost())
1) print
返回無。 因此,您應該將print_item_cost
更改為
def print_item_cost(self):
return '{} {} @ ${} = ${}'.format(self.item_name,
self.item_price,
self.item_quantity,
self.total)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.