首页 > 解决方案 > 将python函数名称设置为变量并尝试访问其函数

问题描述

我正在做一个项目,我收到以下错误:builtins.AttributeError: 'str' object has no attribute 'intro_text' 这可能是一些愚蠢的事情,因为我对 python 还是很陌生,但我一生都无法弄清楚。主要功能如下:

def play():
    world.load_tiles()
    player = Player()
    while player.is_alive() and not player.victory:
        room = world.tile_at(player.x, player.y)
        print(room.intro_text())
        room.modify_player(player)
        if player.is_alive() and not player.victory:
            choose_action(room, player)
        elif not player.is_alive():
            print("Your journey has come to an early end!")

玩家类创建一个新的玩家对象,其中包含 x 和 y 位置、hp、gold 和一个胜利布尔值。问题发生在与print(room.intro_text()). 在它之前的一行中,我们调用了 world.tileat(),它看起来像这样:

def tile_at(x, y):
    if x < 0 or y < 0:
        return None
    try:

        return world_map[y][x]
    except IndexError:
        return None

这个问题出现了,因为我很难编写自己的引擎,并决定从另一个项目中借用一些代码,并用我自己的来补充它。x 和 y 轴位置的东西真的很复杂,而且我目前还没有足够的技能水平来自己编写它。

仅供参考,world文件中的另一个方法是load_tiles(),如下所示:

def load_tiles():
    """Parses a file that describes the world space into the _world object"""
    with open('world/map.txt', 'r') as f:
        rows = f.readlines()
    x_max = len(rows[0].split('\t')) # Assumes all rows contain the same number of tabs
    for y in range(len(rows)):
        row = []
        cols = rows[y].split('\t')
        for x in range(x_max):
            tile_name = cols[x].replace('\n', '') 

            if tile_name == 'startTile':
                global start_tile_location
                start_tile_location = (x, y)    
                #print(start_tile_location)
            row.append(tile_name if tile_name else None)
        world_map.append(row)

world_map以空白列表start_tile_location开始,以None.

整个项目都托管在这里,如果您想真正帮助我并在您的机器上运行它。它应该在 linux 上运行,但它应该可以在 windows 上运行。它唯一需要的模块是随机的,因为它创建了自己的类供使用。

谢谢,我真的被困在这里,感谢我能得到的所有帮助。

标签: pythonpython-3.x

解决方案


推荐阅读