【发布时间】: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