首页 > 解决方案 > 迭代列表时,“方法”对象不可迭代

问题描述

我正在编写一个程序来为我喜欢玩的纸牌游戏评分,并Game()使用以下方法进行以下课程:

def score(self):
    scores = []
    for name in self.players:
      score = name.score_round()
      scores.append(score)
    scores = pd.concat(scores)
    scores = scores.groupby('Player').Score.sum()
    return scores

self.players是在游戏中所有玩家的方法期间制作的列表__init__,每个玩家都有自己的Player()班级。但是,当我调用此方法时,出现以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
----> 1 game.score()

~/dev/code_education/backalley/scoring.py in score(self)
     91   def score(self):
     92     scores = []
---> 93     for name in self.players:
     94       score = name.score_round()
     95       scores.append(score)

TypeError: 'method' object is not iterable

我以为我会遍历一个列表,但我显然错过了一些东西。self.players 等类变量是否也被视为方法?

标签: pythonclass

解决方案


self.players 等类变量是否也被视为方法?

不,但是您正在使用方法名称score(),然后尝试将其附加到列表中。这就是你的问题所在。


推荐阅读