【问题标题】:How to use a method object (which is in the class) outside the class?如何在类外使用方法对象(在类中)?
【发布时间】:2019-03-08 07:51:22
【问题描述】:

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

【问题讨论】:

  • 您忘记为带有 maxcount_inventory 变量的 return_maxcount 提供参数
  • 你为什么使用名称Function_Inventory 作为方法的参数?使用self 几乎是不可侵犯的标准,否则你会混淆你自己和阅读你代码的任何人。
  • @DanielRoseman 我明白了。好的,我会切换到“自我”。
  • @mgracer 如何提供参数?
  • 你不需要参数,你需要实际调用方法:CLASS_INVENTORY().Return_Maxcount()

标签: python python-3.x list function class


【解决方案1】:

我已经重构了你的代码。

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

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

【讨论】:

  • 非常感谢你们太棒了!如果我想打印我所有的库存名称怎么办?
  • @Geni-sama 我在底部为你添加了一个 for 循环。现在它将打印完整列表,然后是每个单独的项目
  • 是的,我也接受这个答案,因为问题中的代码没有使用 self 这不是 OOPS 概念的好兆头。
  • 非常感谢你们。因为你们,我学到了一些东西。我今天很开心。 (对不起帽子)
  • 干杯 :) 我将 for 循环编辑到函数中,然后调用它。稍微清理一下。
【解决方案2】:

在你的代码中改变这个:

maxcount_inventory = CLASS_INVENTORY().Return_Maxcount

到这里:

maxcount_inventory = CLASS_INVENTORY().Return_Maxcount()

还可以更改类中的变量以具有 self.他们前面的前缀 喜欢self.maxcount_inventory 原因是你想调用你的方法,否则它会尝试获取一个变量而不是方法。 您还想将类内函数中的所有参数更改为 self

【讨论】:

    猜你喜欢
    • 2016-08-14
    • 2023-03-26
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多