首页 > 解决方案 > 如何使用字符串变量引用对象?(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'

标签: pythonpython-3.xstringobjectvariables

解决方案


推荐阅读