【问题标题】:TypeError: 'dict' object is not callable fix in python card gameTypeError:'dict'对象在python纸牌游戏中不可调用修复
【发布时间】:2021-01-21 13:19:10
【问题描述】:

类型错误:'dict' 对象不可调用

目前正在为一个项目调试一款纸牌游戏,但不知道如何修复此错误。任何帮助将不胜感激!

 player_info = UI.get_player_information(MAX_PLAYERS)
 self.players = [player_classes(name) for name, typ in player_info]

参考代码:

player_classes = {
'human': Player,
'simple': SmartAI,
'smart': SimpleAI,
}


def get_player_information(max_players):
    """get required information to set up a round"""

    # create players list
    player_info = []
    # how many human players?
    print("\nHow many human players [1-4]:")
    no_of_players = get_int_input(1, max_players)

    # for each player, get name
    for i in range(no_of_players):
        print(f"Please enter the name of player {i+1}:")
        player_info.append(('human', get_string_input()))

    ai_names = ['Angela', 'Bart', 'Charly', 'Dorothy']

    # how many AI players? ensure there are at least 2 players
    min_val = 1 if (len(player_info) == 0) else 0
    max_val = max_players - no_of_players
    print(f"\nHow many ai players [{min_val:d}-{max_val:d}]:")
    no_of_players = get_int_input(min_val, max_val)

    # randomly assign a simple or smart AI for each computer strategy
    for name in ai_names[:no_of_players]:
        if [True, False]:
            player_info.append(('simple', name))
        else:
            player_info.append(('smart', f"Smart {name}"))

    return player_info

【问题讨论】:

  • 您正在尝试player_classes(name),但player_classesdict 而不是function,因此它不可调用。要索引dict,您需要player_classes[name]

标签: python dictionary debugging error-handling


【解决方案1】:

当对象实际上是dict 时,您尝试将player_classes 用作Callable,因此您应该使用符号dict[key] 访问其元素。

您需要将您的list comprehension 更改为

self.players = [player_classes[player_type] for player_type, _ in player_info]

请注意,您正在创建元组,其中 type 作为它们的第一个元素,name 作为第二个元素。

编辑:忘记将变量名称更改为其他名称(type 是 Python 函数)。

【讨论】:

    猜你喜欢
    • 2020-03-24
    • 2016-08-15
    • 2016-03-07
    • 2019-08-10
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2021-04-18
    相关资源
    最近更新 更多