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:

class MyClass(object):
    def max_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"]

    def get_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

class Foo(object):
    list_of_actions = ['action1', 'action2']
    def max_value(self):
        print self.list_of_actions
    def min_value(self):
        print self.list_of_actions        
    def get_action(self):
        list_of_actions = self.list_of_actions[-2::-1]
        print list_of_actions

And here as an instance attribute

class Foo(object):
    def __init__(self):
        self.list_of_actions = ['action1', 'action2']
    def max_value(self):
        print self.list_of_actions
    def min_value(self):
        print self.list_of_actions        
    def get_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

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

def maxvalue(gameState, depth):
    actions = gameState.getLegalActions(0);
    v = -9999
    self.bestaction = []
    for action in actions:
        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..

class Example(object):
  def maxvalue(self, items)
    self.items = items
    return max(item for item in items)

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