【问题标题】:TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'dict'TypeError:'builtin_function_or_method'和'dict'的实例之间不支持'>'
【发布时间】:2019-07-02 07:12:25
【问题描述】:

当我尝试执行此行时,出现此错误 TypeError: '>' not supported between 'builtin_function_or_method'

best_player = max(self.players_scores, self.players_scores.get)

.

这是我的代码:

class Yatzy:
    def __init__(self, humans_num, bots_num):(...)

    @property
    def players_scores(self):
        scores = {}
        for i in range(len(self.humans)):
            scores[self.humans[i].name] = self.humans[i].total_score
        for i in range(len(self.bots)):
            scores[self.bots[i].name] = self.bots[i].total_score
        print(type(self.bots[0].name), type(self.bots[0].total_score))
        return scores

    def game_loop(self):
        print('Welcome to Yatzy game!')
        round_counter = 1
        while round_counter <= self.MAX_ROUNDS:(...)
        print("Final score:", self.players_scores)
        print(type(self.players_scores), type(self.players_scores.keys()), type(self.players_scores.values()))
        best_player = max(self.players_scores, self.players_scores.get)
        print("{} won with {}".format(best_player, self.players_scores[best_player]))

game = Yatzy(humans_num=0, bots_num=4)
game.game_loop()

这是我的打印输出:

Key type: <class 'str'> Value type: <class 'int'>
Final score: {'Bot1': 112, 'Bot2': 110, 'Bot3': 81, 'Bot4': 79}
Key type: <class 'str'> Value type: <class 'int'>
Key type: <class 'str'> Value type: <class 'int'>
Key type: <class 'str'> Value type: <class 'int'>
<class 'dict'> <class 'dict_keys'> <class 'dict_values'>
Key type: <class 'str'> Value type: <class 'int'>
Key type: <class 'str'> Value type: <class 'int'>

    > Traceback (most recent call last):  
 File
    > "C:/Users/Artur/Desktop/Python/yatzy/yatzy.py", line 140, in <module>
    >     game.game_loop()  
 File "C:/Users/Artur/Desktop/Python/yatzy/yatzy.py", line 135, in game_loop
    >     best_player = max(self.players_scores, self.players_scores.get)
 TypeError: '>' not supported between instances of
    > 'builtin_function_or_method' and 'dict'

【问题讨论】:

  • 如果方法不是property,则必须调用它们。
  • 呃我忘了写 key=self.players_scores.get
  • player_scores@property,因此您不必在其上调用get,因为它没有这样的方法...
  • @ArturOwczarek 如果您忘记在问题中添加内容 - 请编辑问题,不要在评论中添加。
  • 我的意思是best_player = max(self.players_scores, self.players_scores.get)应该是best_player = max(self.players_scores, key=self.players_scores.get)。现在可以了。

标签: python python-3.x dictionary


【解决方案1】:

max 的参数必须是数字 - 或者,更具体地说,如您收到的错误消息所示,需要支持相互之间的大于比较(通过实现 Python 的 __gt__ 方法)。如果传入不满足此条件的对象,则会出现错误。

在这种特定情况下,您似乎忘记将第二个参数标识为关键字参数。

best_player = max(self.players_scores, key=self.players_scores.get)

max 也有点特殊,因为它接受一个列表(正如您显然想要的那样)或只是一个非关键字参数序列以作为一个列表进行比较。

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多