我正在尝试根据用户的输入在类中创建任意数量的实例,但到目前为止我无法:
class CLASS_INVENTORY:
maxcount_inventory = int(input("How many Inventories: "))
for count_inventory in range(maxcount_inventory):
def __init__(Function_Inventory, inventory_name(count_inventory)):
add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
inventory_name[count_inventory] = add_inventory
注意:我是Python 3的新手,所以我不确定我的一些语法是否正确。
我希望输出是这样的:
How many Inventories: 4
Enter Inventory #1: Fruits
Enter Inventory #2: Veggies
Enter Inventory #3: Drinks
Enter Inventory #4: Desserts
这是我的完整代码: https://pastebin.com/3FBHgP6i 我还想知道编写 Python 3 代码的规则,如果我正确遵循它们,或者我应该改变一些东西。我希望它对其他Python程序员尽可能易读。
class CLASS_INVENTORY():
maxcount_inventory = int(input("How many Inventories: "))
inventory=[]
def __init__(self):
for count_inventory in range(0, self.maxcount_inventory):
add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
self.inventory.append(add_inventory)
我会做这样的事情:
# Define class
class CLASS_INVENTORY():
# On making a class object init will be called
def __init__(self):
# It will ask for the inventory type count
self.maxcount_inventory = int(input("How many Inventories: "))
self.inventory = []
# Just loop around it to get the desired result
for count_inventory in range(0, self.maxcount_inventory):
add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
self.inventory.append(add_inventory)
输出:
CLASS_INVENTORY()
How many Inventories: >? 2
Enter Inventory #1: >? Apple
Enter Inventory #2: >? Orange
您可以在def _init__(self)
中构建您的二分法,然后设置一个单独的方法print_inventories
,其中包含一个循环来print
,同时保持输入顺序
class Inventory():
def __init__(self):
self.inventories = {}
n = int(input('How many inventories: '))
for i in range(1, n+1):
self.inventories[i] = input('Enter inventory #{}: '.format(i))
def print_inventories(self):
for k in self.inventories:
print('#{}: {}'.format(k, self.inventories[k]))
a = Inventory()
a.print_inventories()
How many inventories: 4 Enter inventory #1: Fruits Enter inventory #2: Veggies Enter inventory #3: Drinks Enter inventory #4: Desserts #1: Fruits #2: Veggies #3: Drinks #4: Desserts