簡體   English   中英

如何使用方法重載添加 2 個類的屬性?

[英]How can I add the attributes of 2 classes using method overloading?

1.我真的有兩個問題。 首先,我得到了意想不到的輸出

None None

從我的最后一行代碼

  1. 對於更難的問題,我需要使用方法重載來添加這兩個項目對象的成本。 我首先提示用戶輸入第 1 項,詢問其名稱、價格和數量。 然后我將價格和數量相乘以獲得這些物品的總數。

我對第二個項目重復此操作,然后我想顯示這兩個項目,並顯示單獨的總計以及合並的總計。 它應該是這樣的

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM