There a several errors in your classes.
First, in Python, you can ger rid of getXXX()
methods, especially in your case. So, you can redefine Item
and User
classes as:
class Item():
"""Name and price of Item"""
def __init__(self, name, price):
self.name = name
self.price = price
class User():
"""Getting name of user"""
def __init__(self, name,budget):
self.name = name
self.budget = budget
In the Cart
class, that code does not what you want:
def addItem(self,carta):
self.carta.append(1) #Adding item in cart.
It will append the integer 1
into the current cart
. To do as you would, take into account the current item to add:
def addItem(self, item):
self.carta.append(item)
Next, getTotal
cannot work as it is:
def getTotal(self, carta): # carta is not needed
total = 0
for item in carta: # work with the current carta, so use self.carta
item = getPrice, getName # I guess you want to retrieve the item's price, so use item.price
total += item
return total
Finally, numItems
cannot work too (!). If you want to find the carta length (as carta
is a list), do that:
def numItems(self): #Number of items in cart.
return len(self.carta)
Final code with fixes and a right print
statement:
class Item():
"""Name and price of Item"""
def __init__(self, name, price):
self.name = name
self.price = price
class User():
"""Getting name of user"""
def __init__(self, name,budget):
self.name = name
self.budget = budget
class Cart():
"""Creating a cart, you can add item in cart and remove it, also u can se your total bill."""
def __init__(self):
self.carta = [] #Carta is shopping cart.
def addItem(self, item):
self.carta.append(item) #Adding item in cart.
def getTotal(self): #Total bill.
total = 0
for item in self.carta:
total += item.price
return total
def numItems(self): #Number of items in cart.
return len(self.carta)
def test_kart():
item1 = Item ("Iphone", 500)
item2 = Item ("Samsung", 200)
item3 = Item("Huawei", 400)
uname = User("Marko", 2000)
kart = Cart()
kart.addItem(item1)
kart.addItem(item2)
kart.addItem(item3)
print('Hi %s, your total bill is $%0.2f, and you have %i items in your cart.' % (uname.name, kart.getTotal(), kart.numItems()))
test_kart()
We can do a lot more pythonic, but it seems you are learning Python, so try to understand that snippet correctly and then try to optimize, if wanted and needed. And read that tutorial 🙂
solved getTotal() takes exactly 2 arguments (1 given) [closed]