Python: TypeError: Can't convert 'generator' object to str implicitly

Python: TypeError: Can't convert 'generator' object to str implicitly

我正在做作业,下面是 class 的样子:

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 函数有什么问题吗?

问题在于您迭代子项并将它们转换为字符串的部分:

(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”。