我有一个方法对象,该对象从类中的用户输入分配了值。问题是我不能在类外使用方法对象maxcount_inventory = int(input("How many Inventories: "))。错误显示为“ method' object cannot be interpreted as an integer

class CLASS_INVENTORY:
    maxcount_inventory = int(input("How many Inventories: "))
    inventory_name = []
    def __init__(Function_Inventory):
        for count_inventory in range(Function_Inventory.maxcount_inventory):
            add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
            Function_Inventory.inventory_name.append(add_inventory)

    def Return_Inventory(Function_Inventory):
        return Function_Inventory.inventory_name

    def Return_Maxcount(Function_Inventory):
        return maxcount_inventory

maxcount_inventory = CLASS_INVENTORY().Return_Maxcount


如果可以的话,另一个问题是,如何在课程外的每个索引中访问列表中的项目?我有下面的代码,但我认为它不起作用。由于上述错误,我尚未发现。

for count_inventory in range(maxcount_inventory):
    class_inv = CLASS_INVENTORY().Return_Inventory[count_inventory]
    print(class_inv)
    skip()


这是我的完整代码:https://pastebin.com/crnayXYy

最佳答案

在这里,我已经重构了代码。

正如@Daniel Roseman提到的,您应该使用self而不是Function_Inventory,所以我更改了它。我还更改了Return_Maxcount的返回值,以根据您的要求提供列表。

class CLASS_INVENTORY:
    maxcount_inventory = int(input("How many Inventories: "))
    inventory_name = []
    def __init__(self):
        for count_inventory in range(self.maxcount_inventory):
            add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
            self.inventory_name.append(add_inventory)

    def Return_Inventory(self):
        for item in self.inventory_name:
            print(item)

    def Return_Maxcount(self):
        return self.inventory_name

maxcount_inventory = CLASS_INVENTORY()
inventory_list = maxcount_inventory.Return_Maxcount()
maxcount_inventory.Return_Inventory()


您可以在底部更改print语句,并将其设置为等于变量的值,以在类本身之外访问它。

关于python - 如何在类外使用方法对象(在类中)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52620995/

10-10 14:13