python-3.x - 位置参数错误并解决它
问题描述
我正在尝试在 python 中实现购物车并拥有此代码,但错误是当我调用 print_menu 函数时,参数不正确。
class ItemToPurchase:
def __init__(self, item_name= 'none', item_price=0, item_quantity=0, item_description = 'none'):
self.item_name = item_name
self.item_price = item_price
self.item_quantity = item_quantity
self.item_description = item_description
def print_item_cost(self):
string = '{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price, (self.item_quantity* self.item_price))
cost = self.item_quantity * self.item_price
return string, cost
def print_item_description(self):
string = '{}: {}'.format(self.item_name, self.item_description)
print(string, end=' ')
return string
class ShoppingCart:
def __init__(self,customer_name= None ,current_date='January 1,2016',cart_items=[]):
self.customer_name = customer_name
self.current_date = current_date
self.cart_items = cart_items
def add_item(self):
print('\nADD ITEM TO CART', end='\n')
item_name = str(input('Enter the item name:'))
item_description = str(input('\nEnter the item description:'))
item_price = int(input('\nEnter the item price:'))
item_quantity = int(input('\nEnter the item quantity:\n'))
self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))
def remove_item(self):
print()
print('REMOVE ITEM FROM CART', end='\n')
string = str(input('Enter name of item to remove:\n'))
i = 0
for item in self.cart_items:
if(item.item_name == string):
del self.cart_items[i]
i += 1
flag=True
break
else:
flag=False
if(flag==False):
print('Item not found in cart. Nothing removed.')
def modify_item(self):
print('\nCHANGE ITEM QUANTITY', end='\n')
name = str(input('Enter the item name:'))
for item in self.cart_items:
if(item.item_name == name):
quantity = int(input('Enter the new quantity:'))
item.item_quantity = quantity
flag=True
break
else:
flag=False
if(flag==False):
print('Item not found in cart. Nothing modified.')
def get_num_items_in_cart(self):
num_items = 0
for item in self.cart_items:
num_items += item.item_quantity
return num_items
def get_cost_of_cart(self):
total_cost = 0
cost = 0
for item in self.cart_items:
cost = (item.item_quantity * item.item_price)
total_cost += cost
return total_cost
def print_total(self):
total_cost = self.get_cost_of_cart()
if (total_cost == 0):
print('SHOPPING CART IS EMPTY')
else:
self.output_cart()
def print_descriptions(self):
print('OUTPUT ITEMS\' DESCRIPTIONS')
print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date),end='\n')
print('\nItem Descriptions', end='\n')
for item in self.cart_items:
print('{}: {}'.format(item.item_name, item.item_description), end='\n')
def output_cart(self):
new=ShoppingCart()
print('OUTPUT SHOPPING CART', end='\n')
print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date),end='\n')
print('Number of Items:', new.get_num_items_in_cart(), end='\n\n')
self.total_cost = self.get_cost_of_cart()
if (self.total_cost == 0):
print('SHOPPING CART IS EMPTY')
else:
pass
tc = 0
for item in self.cart_items:
print('{} {} @ ${} = ${}'.format(item.item_name, item.item_quantity,
item.item_price, (item.item_quantity * item.item_price)), end='\n')
tc += (item.item_quantity * item.item_price)
print('\nTotal: ${}'.format(tc), end='\n')
def print_menu(ShoppingCart):
customer_Cart = newCart
string=' '
#declare the string menu
menu = ('\nMENU\n'
'a - Add item to cart\n'
'r - Remove item from cart\n'
'c - Change item quantity\n'
'i - Output items\' descriptions\n'
'o - Output shopping cart\n'
'q - Quit\n')
command = ''
#Using while loop
#to iterate until user enters q
while(command != 'q'):
string=''
print(menu, end='\n')
#Prompt the Command
command = input('Choose an option: ')
#repeat the loop until user enters a,i,r,c,q commands
while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'):
command = input('Choose an option: ')
#If the input command is a
if(command == 'a'):
#call the method to the add elements to the cart
customer_Cart.add_item(string)
#If the input command is o
if(command == 'o'):
#call the method to the display the elements in the cart
customer_Cart.output_cart()
#If the input command is i
if(command == 'i'):
#call the method to the display the elements in the cart
customer_Cart.print_descriptions()
#If the input command is i
if(command == 'r'):
customer_Cart.remove_item()
if(command == 'c'):
customer_Cart.modify_item()
if __name__ == "__main__":
customer_name = str(input('Enter customer\'s name:'))
current_date = str(input('\nEnter today\'s date:'))
print()
print()
print('Customer name:', customer_name, end='\n')
print('Today\'s date:', current_date, end='\n')
newCart = ShoppingCart(customer_name, current_date)
newCart.print_menu(newCart)
我已经创建了类 ShopppingCart 的实例,但它不工作。我正在尝试获取用户输入,然后显示菜单供用户选择和实现购物车类中定义的功能之一。谁能帮我解决这个问题。
解决方案
这个问题是由于函数的参数ShoppingCart发生的。您调用了第一个参数 ShoppingCart,它实际上是 ShoppingCart 对象;通常这是自我论证。Python 不在乎你给它起什么名字:self、ShoppingCart、corona。第一个参数将始终是调用该函数的对象。使用这些代码行调用此函数时:
newCart = ShoppingCart(customer_name, current_date)
newCart.print_menu(newCart)
您正在使用 newCart 对象调用该函数,然后将newCart对象作为参数传递。你不需要这样做。Python 已经传递了该对象,因此您不必这样做。
我假设这是您收到的错误:
Traceback (most recent call last):
File "c:/Users/jeffg/Desktop/ProgrammingProjects/StackOverFlow/shoppingcart.py", line 246, in <module>
newCart.print_menu(newCart)
TypeError: print_menu() takes 1 positional argument but 2 were given
发生此错误是因为您的函数被定义为仅接受一个参数。你没有解释self论点。要解决此问题,需要将代码修改为以下内容:
def print_menu(self, newCart):
customer_Cart = newCart
尽管如前所述,您不需要传递 newCart 对象,因为您已经可以使用self访问 newCart 对象。然后,您可以将功能精简为:
def print_menu(self):
而不是使用customer_Cart来调用函数,您可以使用 self:
while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'):
command = input('Choose an option: ')
if(command == 'a'):
self.add_item(string)
我还建议使用elif语句,而不是在 print_menu() 函数中使用大量if 语句。
推荐阅读
- azure - Cosmos Db 吞吐量
- azure - 如何触发 Azure Logic App 中的工作流以及触发器作为输入的参数?
- youtube-api - 如何从 Youtube 中删除“更多视频”功能
- reactjs - PassportJs 在反应应用程序的页面刷新时获取登录用户的详细信息
- json - 以角度传递字符串类型的输入字段值
- vb.net - 集合之间的差异
和自定义实现类 - sql - 是否有一种简洁的方法可以对 SQL 查询的所有列执行相同的合并?
- sql - SQL 按辅助 ID 上的类型过滤
- amazon-web-services - 在同一个 S3 存储桶中跨文件夹移动文件
- php - 多次调用一个函数并将所有值作为单个列表 php