简体   繁体   中英

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

1.I really have 2 questions. First I am getting unexpected output of

None None

from my last line of code

  1. For the harder question I need to use method overloading to add the cost of these two item objects. I first prompt the user for item 1 asking for its name, price then quantity. I then multiply the price and the quantity to get that items total.

I repeat this for the second item I then want to display the two items and there separate total as well as the combined total. It should look like this

TOTAL COST
Apple 3 @ $2 = $6
Balls 4 @ $4 = $16

Total: $22

I'm getting this instead

TOTAL COST

x 3 @ $2 = $6
y 6 @ $4 = $24
None None

I don't know where the "None None" is coming from or how to remove it without the item info getting removed and I don't know how to combine the cost using overloading. I have what looks like a solution in the add method here with my code

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 returns None. Therefore, you should change print_item_cost to

def print_item_cost(self):
        return '{} {} @ ${} = ${}'.format(self.item_name,
                                              self.item_price,
                                              self.item_quantity,
                                              self.total)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM