Skip to content Skip to sidebar Skip to footer

How To Access The List In Different Function

I have made a class in which there are 3 functions. def maxvalue def min value def getAction In the def maxvalue function, I have made a list of actions. I want that list to be

Solution 1:

It's a good idea to post actual code - it makes it easier to see what's happening.

With that said, you probably want something like this:

classMyClass(object):
    defmax_value(self):
        # assigning your list like this will make it accessible # from other methods in the class
        self.list_in_max_value = ["A", "B", "C"]

    defget_action(self):
        # here, we're doing something with the list
        self.list_in_max_value.reverse()
        return self.list_in_max_value[0]

>>> my_class = MyClass()
>>> my_class.max_value()
>>> my_class.get_action()
"C"

You might want to read through the python class tutorial.

Solution 2:

Either define the list as a class attribute or as an instance attribute, then all the methods will be able to access it

If you'd like to post your class, it'll be easier to show you what I mean

Here is an example making it a class attribute

classFoo(object):
    list_of_actions = ['action1', 'action2']
    defmax_value(self):
        print self.list_of_actions
    defmin_value(self):
        print self.list_of_actions        
    defget_action(self):
        list_of_actions = self.list_of_actions[-2::-1]
        print list_of_actions

And here as an instance attribute

classFoo(object):def__init__(self):
        self.list_of_actions = ['action1', 'action2']
    defmax_value(self):
        print self.list_of_actions
    defmin_value(self):
        print self.list_of_actions        
    defget_action(self):
        list_of_actions = self.list_of_actions[-2::-1]
        print list_of_actions

Edit since you posted code, here is how to fix your problem

defgetAction(self,gamestate):
    self.bestaction.reverse()
    return bestaction[0]

defmaxvalue(gameState, depth):
    actions = gameState.getLegalActions(0);
    v = -9999self.bestaction = []
    for action inactions:
        marks = minvalue(gameState.generateSuccessor(0, action), depth, 1)
        if v < marks:
            v = marks
        self.bestaction.append(action)
    return

Solution 3:

You could use a side effect to create an attribute of the class..

classExample(object):
  defmaxvalue(self, items)
    self.items = items
    returnmax(item for item in items)

Post a Comment for "How To Access The List In Different Function"