这是我的代码:
print ("Welcome to our Shop")
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
def getName(self): #Returning name of Item.
return self.name
def getPrice(self): #Returning price of Item.
return self.price
class Cart:
def __init__(self, list):
self.list = [] #List is Cart, you will store items in it.
def addItem(self, item):
self.item = list.append(self.list) #Adding item to Cart(List).
def getTotal(self): #Total price. Your bill.
total = 0
for item in self.list:
total += price
return total
def numItems(self): #Number of items in your cart.
items = 0
for item in self.list:
items += item
def kart():
item1 = Item("Xbox", 350)
item2 = Item("Controller", 50) #Items to buy.
item3 = Item("LED TV 55", 550)
k = Cart() #Calling Cart Class.
k.addItem(item1)
k.addItem(item2) #Adding Items.
k.addItem(item3)
print ("You have %i items in your cart for a total of %s $" %(k.numItems(), k.getTotal()))
korpa = kart()
我最后得到错误。它说
Welcome to our ShoTraceback (most recent call last):
File "C:\Users\Marko\Documents\Projects\EbayCart.py", line 41, in <module>
p
korpa = kart()
File "C:\Users\Marko\Documents\Projects\EbayCart.py", line 35, in kart
k = Cart() #Calling Cart Class.
TypeError: __init__() takes exactly 2 arguments (1 given)
[Finished in 0.1s with exit code 1]
我正在读书
__init__() takes exactly 2 arguments (1 given)
帖子,但在我的案例中没有帮助。 你有什么想法有什么问题吗? 我现在正在学习课程以及这段代码的目的。 感谢您的帮助。
答案 0 :(得分:1)
您正在定义cart init以获得列表参数
def __init__(self, list)
然后不带参数调用它:
k = Cart()
根据你的init定义,你必须用
之类的东西创建一个带有空列表的实例k = Cart([])
但是当你仔细观察init
函数时,你会发现事实上你并没有使用list
,所以就这样放弃它:
class Cart:
def __init__(self):
self.list = [] #List is Cart, you will store items in it.
答案 1 :(得分:0)
Cart的__init__
接受了一个参数list
,您可能并不需要提供它,因为它只是一个空列表,您将在以后填写。您只需将init类更改为
def __init__(self):
self.list = []
将项目添加到列表中也不能正常工作,但我认为如果您首先尝试自己解决该问题会更好......:)