Python Class 位置变量

Python Class Location Variables

我想降低玩家的生命值,但我不确定我是否能够做到这一点,如果这个问题不清楚,我很抱歉,但我是一个新的编码员,我正在慢慢掌握 classes工作。我想我需要尽可能说清楚。

class Health(object): 
#health of player and enemy
#input of the both health so it is able to
#be a preset for more combat

    def __init__(self, player, enemy):

        self.player = player
        self.enemy = enemy

class Attack_Type(object):
#making a attack type blueprint
#combat attacks can be modified

    def melee(self, target):
        #100% chance of landing hit
        if target == player:
            Health.player -= 1
            return Health.player
        elif target == enemy:
            Health.enemy -= 1
            return Health.enemy

test = Health(10,10)
enemy_melee = Attack_Type(Health.player)

我的问题是如何在不使其成为全局变量的情况下访问 class 中的变量值。我可以更改 class 中的 class 值吗? 这不会改变玩家的生命值,因为它无法访问玩家的生命值,但即使它这样做也不会 return 值到正确的位置

我现在意识到将健康作为一个属性要简单得多,对不起大家我不完全理解class它是如何工作的!感谢大家的帮助!

这是一个化身。

class Health:
    def __init__(self):
        self.player_health = 10
        self.enemy_health = 10


class Combat:
    def attack(self, health_obj):
        health_obj += -1
        return health_obj

bridge = Combat()
players = Health()

print(bridge.attack(players.player_health))

希望对您有所帮助! :)

class Health:
    def __init__(self): #Constructor initializing the variables.
        self.player_health = 10
        self.enemy_health = 10

class Combat:
    #Attack function receives a health object called "hitter" 
    def attack(self, hitter):
        hitter.player_health -= 1   #Health Object hitter's player_health reduced by one. 
        return hitter

bridge = Combat() #Combat Object
hitter = Health() #Health Object

bridge.attack(hitter) #hitter.player_health is now 9.