如何在不同函数中访问列表

-1 投票
3 回答
2721 浏览
提问于 2025-04-16 02:10

我创建了一个类,这个类里面有三个函数。

  1. def maxvalue
  2. def min value
  3. def getAction

在maxvalue这个函数里,我创建了一个动作的列表。我希望在getAction这个函数里也能访问到这个列表,这样我就可以把列表反转,然后取出第一个元素。请问我该怎么做呢?

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




 def maxvalue(gameState, depth):

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

但是它给我报错了……“全局名称bestaction未定义”

3 个回答

0

你可以使用副作用来创建这个类的一个属性。

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

你可以把这个列表定义为类的属性,或者定义为实例的属性,这样所有的方法就都能访问到它了。

如果你把你的类发出来,那我就能更清楚地告诉你我想表达的意思。

下面是一个把它定义为类属性的例子。

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

这里是把它定义为实例属性的例子。

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

编辑:既然你已经发了代码,这里是解决你问题的方法。

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
1

发一些实际的代码是个好主意,这样大家更容易理解发生了什么。

话说回来,你可能想要这样的代码:

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"

你可以看看这个Python类的教程

撰写回答