You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何通过字符串变量引用对应类实例对象及其属性?

问题原因

你代码中opponent = "player_"+str(opponent_index)生成的是字符串格式的变量名文本,而非你预先定义的Player类实例对象,字符串本身没有hp属性,因此触发属性报错。

最优解决方案

不要通过拼接变量名的方式获取实例,直接将所有玩家实例存入一维列表,通过索引直接读取对应实例,代码可维护性和稳定性更高,修改步骤如下:

  1. 定义所有玩家的一维索引列表,索引和opponent_index的0-9一一对应
  2. 修改shoot函数中获取对手实例的逻辑,直接从列表中按索引读取

修正后完整代码

import random

class Player:
    def __init__(self, hp, armor, weapon, pistol):
        self.hp = hp
        self.armor = armor
        self.weapon = weapon
        self.pistol = pistol

player_1 = Player(100, 100, "AK-47", "Glock-18")
player_2 = Player(100, 100, "AK-47", "Glock-18")
player_3 = Player(100, 100, "AK-47", "Glock-18")
player_4 = Player(100, 100, "AK-47", "Glock-18")
player_5 = Player(100, 100, "AK-47", "Glock-18")
player_6 = Player(100, 100, "AK-47", "Glock-18")
player_7 = Player(100, 100, "AK-47", "Glock-18")
player_8 = Player(100, 100, "AK-47", "Glock-18")
player_9 = Player(100, 100, "AK-47", "Glock-18")
player_0 = Player(100, 100, "AK-47", "Glock-18")

# 新增:按索引0-9对应存储所有玩家实例
all_players = [player_0, player_1, player_2, player_3, player_4, player_5, player_6, player_7, player_8, player_9]

def shoot(player, p_index):
    opponent_index = random.randint(0, 9)
    while opponent_index == p_index:
        opponent_index = random.randint(0, 9)
    # 修改:直接从列表获取实例,不再拼接字符串
    opponent = all_players[opponent_index]

    # 修复变量名冲突:原代码用shoot作为变量名会覆盖同名函数,改为is_hit
    is_hit = random.randint(1, 10) < 4

    if player.weapon == "AK-47" and is_hit:
        print(f"击中对手,对手原hp:{opponent.hp}")
        opponent.hp -= 25

team_VoidWave = [player_1, player_2, player_3, player_4, player_5]
team_Renegades = [player_6, player_7, player_8, player_9, player_0]
players = [team_VoidWave, team_Renegades]

print(player_0.hp, player_1.hp, player_2.hp, player_3.hp, player_4.hp, player_5.hp, player_6.hp, player_7.hp, player_8.hp, player_9.hp)

shoot(player_2, 2)

print(player_0.hp, player_1.hp, player_2.hp, player_3.hp, player_4.hp, player_5.hp, player_6.hp, player_7.hp, player_8.hp, player_9.hp)

补充说明

如果确实需要通过字符串形式的变量名获取全局对象,可以使用globals()内置方法:

opponent = globals()["player_"+str(opponent_index)]

该写法不推荐使用,会大幅降低代码可读性和可维护性,同时容易出现变量名匹配错误。

内容的提问来源于stack exchange,提问作者delsix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:15:03