首页 > 解决方案 > 如何在类外使用方法对象(在类中)?

问题描述

我有一个方法对象,它从类中的用户输入中分配了值。问题是我不能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

标签: pythonpython-3.xlistfunctionclass

解决方案


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

正如@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()

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


推荐阅读