首页 > 解决方案 > 库存系统添加新对象而不是数量增加 1

问题描述

我正在尝试建立一个库存系统,在该系统中获取您已经拥有的物品只会增加物品的数量,而不是在列表中添加一个全新的物品。


def enc1():
  print("hello")

def enc2():
  print("hi")

def enc3():
  print("howdy")

def enc4():
  print("hey")

def enc5():
  print("heyo")

class item:
  def __init__(self, name, amount):
    self.name = name
    self.amount = amount

items = []

apple = item("apple", 1)

def addItem(itemToAdd):
  for x in items:
    if(x == itemToAdd):
      itemToAdd.self.amount += 1
    else:
      items.append(itemToAdd)

addItem(apple)
print(items, apple.amount)
addItem(apple)
print(items, apple.amount)

encounter = random.randint(1,5)

if(encounter == 1):
  enc1()
elif(encounter == 2):
  enc2()
elif(encounter == 3):
  enc3()
elif(encounter == 4):
  enc4()
elif(encounter == 5):
  enc5()

标签: pythoninventory

解决方案


推荐阅读