Python 为什么我会收到此错误“TypeError: 'method' object is not iterable”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35509744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:32:05  来源:igfitidea点击:

Why do I get this error "TypeError: 'method' object is not iterable"?

pythonpython-3.x

提问by Jessy White

I do not understand how a list can not be iterable. We initialized the list and used it to add pieces of a jigsaw puzzle inside the list.

我不明白列表如何不能迭代。我们初始化了列表,并用它在列表中添加了拼图的碎片。

The user is to input the amount of rows and column they want the board to be. Each row is a new piece and each column is a new piece. Each piece is a list of 3 lists to look like a matrix. My idea was to create a list pieces=[] and append the list with each new generated piece.

用户将输入他们想要的板的行数和列数。每一行都是一个新的作品,每一列都是一个新的作品。每个部分都是一个由 3 个列表组成的列表,看起来像一个矩阵。我的想法是创建一个列表pieces=[] 并将列表附加到每个新生成的作品中。

My problem is that i can't get the str() to print the board out. I was thinking we should print the first list of the 3 lists of each piece in the pieces list and then for the middle list of the 3 lists and then the last list of the three lists. And start at a new line. I do know how to implement it though.

我的问题是我无法让 str() 打印出电路板。我在想我们应该打印pieces列表中每个部分的3个列表的第一个列表,然后打印3个列表的中间列表,然后打印三个列表的最后一个列表。并从新行开始。我确实知道如何实施它。

Or I was thinking i could just print each piece alone and then add pieces to that string to print out the board. So i would not be using the pieces=[] list. I don't know which is best or how to implement them.

或者我想我可以单独打印每一块,然后将碎片添加到该字符串中以打印出电路板。所以我不会使用pieces=[] 列表。我不知道哪个最好或如何实施它们。

I tried looking at other questions but I could not find an answer, I try to print the string representation of the class:

我尝试查看其他问题,但找不到答案,我尝试打印该类的字符串表示形式:

from random import randint
from pprint import pprint


class Jigsaw:

    def __init__(self, r, c):
        self.pieces = []
        self.row = r
        self.col = c

    def __str__(self):
        """
        Writes the state and value to a string.
        """
        s =" "
        d = ""
        f = ""
        g = ""
        for row in self.pieces:
        #print(row)
            for col in row:
               #print(col)
                d = d +" "+ format(col[0])
        print(d)
        for row in self.pieces:
            #print(row)
            for col in row:
            #print(col)
                f = f +" " + format(col[1])
        print(f)

        for row in self.pieces:
            #print(row)
            for col in row:
                #print(col)
                g = g +" "+ format(col[2])
        print(g)



    #     return pce
    # result = 'ball : %s' \
    #     % (pce)
        #return r

    def __repr__(self):
        """
        Returns the string representation.
        """
        return str(self)

    def puzzle_board(self):
        for c in range(self.row):
            for d in range(self.col):
                self.pieces.append(self.add_piece)

        return self.pieces

    def add_piece(self):
        a = PieceGenerator()
        b = self.a_piece(a.idn,a.top,a.left,a.right,a.bottom)
        self.pieces.append(b)
        return(b)


    def mis(self):
        self.add_piece()

     # def boardShuffle(self,board):

    def a_piece(self, id, top,left,right,bottom):
        """
        Returns the piece values.
        """
        pce = [[" ", top, " "], [left, id, right], [" ", bottom, " "]]
        return(pce)

    # def puzzleSolve(self,board):

class PieceGenerator:
    """
    Creates new puzzle pieces with their values.
    """
    idn = 0 #Global variable to keep track of all the pieces
    def __init__(self):
        """
        A piece have top, bottom, right, left values and puzzle piece it self
        """
        self.top = randint(10,99)
        self.bottom = randint(10,99)
        self.right = randint(10,99)
        self.left = randint(10,99)
        PieceGenerator.idn += 1

print(Jigsaw(3,5).puzzle_board())

Here is the error I get:

这是我得到的错误:

Traceback (most recent call last):
   File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 102, in    <module>
    print(Jigsaw(3,5).puzzle_board())
   File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 56, in  __repr__
    return str(self)
   File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 22, in __str__
    for col in row:
TypeError: 'method' object is not iterable

回答by Thomas Lotze

You misunderstand the error message: It doesn't say that a list would not be iterable, it says that a method isn't.

您误解了错误消息:它并不是说列表不可迭代,而是说方法不可迭代。

What happens is that your pieceslist doesn't contain pieces but references to the add_piecemethod because you forgot to call the method when you wanted to append its result in line 56.

发生的情况是您的pieces列表不包含片段,而是对add_piece方法的引用,因为当您想在第 56 行附加其结果时忘记调用该方法。

You could have found this error even having less experience with exception types by invoking a debugger (pdb) just before the line that raises the error.

通过pdb在引发错误的行之前调用调试器 ( ),即使对异常类型的经验较少,您也可以发现此错误。