python - 如何在类外使用方法对象(在类中)?
问题描述
我有一个方法对象,它从类中的用户输入中分配了值。问题是我不能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()
您可以更改底部的打印语句并将其设置为等于一个变量以在类本身之外访问它。
推荐阅读
- python - 熊猫根据使用超过 20 列的条件为多个列分配值
- php - CentOs7 上的 php exec() 但中止 errno 134
- blogger - 如何通过 html 在 Blogger 中添加自定义 Favicon?
- sql-server-2016 - 如何将 varchar 列与多个值进行比较
- typescript - 如何在 Pulumi 中找到现有的 gitlab 项目集群?
- kubernetes - 是否可以从其他用户部署的集群中获取 helm list
- python - 无法导入“crispy_forms.helper”-Pylint
- vba - Selenium VBA - 如何将鼠标移动到位置(x,y)?
- php - 请帮助修复无法加载动态库
- reactjs - 我如何测试对象内部的函数调用?