python - 如何使用字符串变量引用对象?(Python)
问题描述
我想引用对象的属性 hp,但控制台说字符串对象没有属性“hp”。据我了解,它将变量作为字符串,但是我如何引用实际的player_x.hp
其他方式?
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")
def shoot(player, p_index):
opponent_index = random.randint(0, 9)
while opponent_index == p_index:
opponent_index = random.randint(0, 9)
opponent = "player_"+str(opponent_index)
shoot = random.randint(1, 10)
if shoot < 4:
shoot = True
if player.weapon == "AK-47":
print(404)
print(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)
控制台:回溯(最近一次调用最后):文件“C:\Users\38099\PycharmProjects\pythonProject\main.py”,第 46 行,在拍摄中(player_2, 2)文件“C:\Users\38099\PycharmProjects\pythonProject \main.py",第 35 行,在拍摄打印(opponent.hp)中 AttributeError:'str' 对象没有属性 'hp'
解决方案
推荐阅读
- php - 重构以符合 DRY 原则
- debugging - 在 Clojure 中调试线程宏 -> 或 ->>
- swift - 我在 tvos 应用中播放 .mp4 网址时遇到问题
- node.js - 有来自快速服务器的客户端访问文件:base64 还是文件的绝对路径?
- php - 使用复选框意外更改归档值
- android - 在 Kotlin Android 中使用 DynamoDBMapper 会引发错误
- python-3.x - 使用 autopy 将光标移动到图像时出现问题
- regex - Fail2Ban 正则表达式排除如果/在某个点之后找到
- python - 按行总和对矩阵进行排序
- python - 从 Vpython 几何对象继承