我做了一个有3个功能的课程。
在def maxvalue函数中,我制作了一个动作列表。我希望在def 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”
答案 0 :(得分: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 :(得分: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"
您可能想要阅读the python class tutorial。
答案 2 :(得分:0)
您可以使用副作用来创建类的属性..
class Example(object):
def maxvalue(self, items)
self.items = items
return max(item for item in items)