2015-04-03 57 views
2

我在做一个任务,并在这里是类的样子:的Python:类型错误:无法将“发电机”对象为str隐含

class GameStateNode: 
    ''' 
    A tree of possible states for a two-player, sequential move, zero-sum, 
    perfect-information game. 

    value: GameState -- the game state at the root of this tree 
    children: list -- all possible game states that can be reached from this 
    game state via one legal move in the game. children is None until grow 
    is called. 
    ''' 

    def __init__(self, game_state): 
     ''' (GameStateNode, GameState) -> NoneType 

     Initialize a new game state tree consisting of a single root node 
     that contains game_state. 
     ''' 
     self.value = game_state 
     self.children = [] 

然后我,因为我需要写的这两个功能一个递归str:

def __str__(self): 
     ''' (GameStateNode) -> str '''  
     return _str(self) 

def _str(node): 
    ''' (GameStateNode, str) -> str ''' 
    return ((str(node.value) + '\n') + 
      ((str(child) for child in node.children) if node.children else '')) 

有人可以告诉我什么是我的_str函数的问题?

回答

3

问题是部分地方你遍历儿童并将其转换为字符串:

(str(child) for child in node.children) 

这实际上是一个generator expression,这不能简单地转换为字符串,然后连接起来用左手部分str(node.value) + '\n'

在进行字符串连接之前,您应该通过调用join将由生成器创建的字符串连接到单个字符串中。像这样的东西会用逗号连接字符串:

','.join(str(child) for child in node.children) 

最终,你的代码也许应该简化为像

def _str(node): 
    ''' (GameStateNode, str) -> str ''' 
    return (str(node.value) + '\n' + 
     (','.join(str(child) for child in node.children) if node.children else '')) 

当然,你也可以与其他一些字符加入字符串或字符串,如'\ n',如果你想。

+0

作品!太感谢了! – FistLauncher 2015-04-03 05:53:56

+0

不客气。 ;) – hgazibara 2015-04-03 05:54:20

相关问题