0

I want to refer to object's attribute hp, but console says that string object has no attribute "hp". As I understand it takes the variable as a string, but how can I refer to an actual player_x.hp other way?

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)

Console: Traceback (most recent call last): File "C:\Users\38099\PycharmProjects\pythonProject\main.py", line 46, in shoot(player_2, 2) File "C:\Users\38099\PycharmProjects\pythonProject\main.py", line 35, in shoot print(opponent.hp) AttributeError: 'str' object has no attribute 'hp'

not_speshal
  • 22,093
  • 2
  • 15
  • 30
delsix
  • 1
  • store your players in a list instead of naming them _1 etc, and this problem becomes irrelevant – Sayse Oct 27 '21 at 12:38
  • 1
    You know how when you do `team_VoidWave = [player_1, player_2, player_3, player_4, player_5]`, it allows you to refer to `team_VoidWave[0]` etc. instead of having to come up with a separate variable name for each player? What if you tried doing that for the entire group of players in the first place? If you had a list like that, can you think of a way that you could replace the `opponent = "player_"+str(opponent_index)` code in order to take advantage of that list? – Karl Knechtel Oct 27 '21 at 12:40
  • In the method shoot, the opponent object is string and not of type Player – s510 Oct 27 '21 at 12:43

0 Answers0