TypeError:“ builtin_function_or_method”和“ dict”的实例之间不支持“>”

时间:2019-07-02 07:12:25

标签: python python-3.x dictionary

当我尝试执行此行时,出现'buildin_function_or_method'实例之间不支持此错误TypeError:'>'

  

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'

1 个答案:

答案 0 :(得分:0)

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

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

__gt__

best_player = max(self.players_scores, key=self.players_scores.get) 的特殊之处还在于它可以接受列表(如您所预期的那样),也可以接受一系列非关键字参数作为列表进行比较。