【问题标题】:Call a stored method on a object [duplicate]在对象上调用存储方法[重复]
【发布时间】:2019-10-10 16:37:19
【问题描述】:


我有一个希望应用于对象列表的方法列表。对象包含将改变方法结果的信息。然后我将存储得到我想要的结果的对象。
代码如下所示:其中 chefs 是应该对 ingredient 执行 action 的对象。

我收到此错误 AttributeError: 'Chef' object has no attribute 'possibleAction'
似乎编译器没有从 possibleAction (我想要的)中获取值,而只是获取变量的名称。

我不确定这是否可行,但我知道您可以将函数存储在变量中然后调用它们,所以这可能也适用于我认为的方法。无论如何,我正在寻求我能得到的所有帮助,干杯:)

possibleStates = []
for chef in state.getChefs():
    for possibleAction in getAllPossibleActionForChef():
        for ingredient in state.getKitchen().getIngredients():
            newPossibleState = copy.copy(state)
            if chef.possibleAction(ingredient):              # Do doAction on state, if true save else trow away
                possibleStates.append(newPossibleState)
return possibleStates

【问题讨论】:

  • 究竟什么(数据类型)包含“possibleAction”?
  • 变量possibleAction与属性访问.possibleAction无关。您想使用getattr 来动态访问带有字符串的属性
  • 另外,方法和函数的区别在这里也无关紧要。
  • @juanpa.arrivillaga getattr 似乎是去这里的路,我明天会仔细检查。我问为什么这里的区别无关紧要?
  • @MichaelButscher possibleAction 是我可以从 chef 对象获得的方法列表。我使用此代码来获取它,然后修剪掉标准代码,因此列表中只剩下我实现的函数。 objectMethods = [dir(Chef) 中 method_name 的方法名 if callable(getattr(Chef, method_name))]

标签: python python-3.x object methods


【解决方案1】:

使用getattr使用字符串获取你想要的方法:

getattr(chef, possibleAction)(ingredient)

【讨论】:

  • 我试过了,看起来很有希望。在我选择这个答案作为解决方案之前,我将在明天仔细检查所有内容。同时感谢您的回答,我很高兴
【解决方案2】:

chef.possibleAction(配料): 该语句表明 possibleAction() 是一个实例方法,属于 chef 类或其父类,可以由 chef 对象调用。 确保 chef 类在其或其父类中包含 possibleAction 方法声明。

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多