我有一个方法对象,该对象从类中的用户输入分配了值。问题是我不能在类外使用方法对象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
答案 0 :(得分:3)
在这里,我重构了代码。
就像@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语句,并将其设置为等于变量的值,以在类本身之外访问它。
答案 1 :(得分:1)
在您的代码中只需更改以下内容即可:
maxcount_inventory = CLASS_INVENTORY().Return_Maxcount
对此:
maxcount_inventory = CLASS_INVENTORY().Return_Maxcount()
还将类中的变量更改为具有self。在他们之前加前缀
像self.maxcount_inventory
原因是您要调用方法,否则它将尝试获取变量而不是方法。
您还希望将类内部函数中的所有参数更改为self