如何使用用户输入在类中创建实例?

时间:2018-10-03 01:31:20

标签: python python-3.x function class user-input

我正在尝试根据用户的输入在类中创建任意数量的实例,但是到目前为止,我无法:

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程序员尽可能地易读。

3 个答案:

答案 0 :(得分:1)

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) 

答案 1 :(得分:0)

我会做这样的事情:

# 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

答案 2 :(得分:0)

您可以在def _init__(self)内构造 diciptonary ,然后设置一个单独的方法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