0


I have a list of methods that i wish to apply on a list of objects. The objects contain info that will change the outcome of the methods. I will then store the objects that got an outcome that i want.
The code looks as the following: where chefs is the objects that should carry out an action on an ingredient.

I am getting this error AttributeError: 'Chef' object has no attribute 'possibleAction'
It seems like the compiler does not take the value from possibleAction (which i want) and instead just take the name of the variabel.

I am not sure if this is possible but i know that you can store function in variabels and then call them, so then this maybe works on methods too i thought. Anyway i am appriacting all the help i can get, cheers :)

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
Johnboll
  • 55
  • 9
  • What exactly (datatype) contains "possibleAction"? – Michael Butscher Oct 10 '19 at 16:47
  • 1
    The variable `possibleAction` will have no relation to the attribtue access `.possibleAction`. You want to use `getattr` to dynamically access attribtues with strings – juanpa.arrivillaga Oct 10 '19 at 18:51
  • Also, the distinction between methods and functions is irrelevant here. – juanpa.arrivillaga Oct 10 '19 at 18:53
  • @juanpa.arrivillaga getattr seems like the way to go here, i will double check tommorow. My i ask why the distinction is irrelevant here? – Johnboll Oct 10 '19 at 20:32
  • @MichaelButscher possibleAction is a list of of methods that i can get from the chef object. I used this code to get it and then trimmed away the standard ones so only my implemented function is left in the list. objectMethods = [method_name for method_name in dir(Chef) if callable(getattr(Chef, method_name))] – Johnboll Oct 10 '19 at 20:34

2 Answers2

1

Use getattr to get the method you want using a string:

getattr(chef, possibleAction)(ingredient)
N Chauhan
  • 3,407
  • 2
  • 7
  • 21
  • I tried this and it looks promising. I will just double check everything tommorow before i choose this answer as solution. Thank you for your answer meanwhile, I appriciate it – Johnboll Oct 10 '19 at 20:29
0

chef.possibleAction(ingredient): This statement indicates that possibleAction() is an instance method belonging either to chef class or its parent class which can be called by chef object. Ensure that chef class contains the possibleAction method declaration in it or in its parent class.