Python类位置变量

Python类位置变量,python,class,variables,localization,Python,Class,Variables,Localization,我想减少球员的健康,但我不确定我是否能够做到这一点,抱歉,如果这个问题不清楚,但我是一个新的编码员,正在慢慢掌握如何类工作。我想我需要尽可能把这件事说清楚 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):

我想减少球员的健康,但我不确定我是否能够做到这一点,抱歉,如果这个问题不清楚,但我是一个新的编码员,正在慢慢掌握如何类工作。我想我需要尽可能把这件事说清楚

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 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))
我希望这有帮助!:)


player\u health=bridge.attack(player\u health)
做你想做的事吗?@Paul ruoney不,第14Ok行出现了一个trackback,说“player\u health”没有定义。抱歉,我以为您没有显示所有代码。玩家的健康状况应该是某种类型的对象还是一个整数?只需在最后一行之前添加
player\u health=0
。我不明白你想做什么这是一个非常有趣的课堂使用,但是我认为如果你将
健康
作为
玩家
类的属性,而不是拥有一个包含每个人健康的
健康
对象,你可能会更轻松。@TigerhawkT3是的,你是对的,在类外使用属性要容易得多,我一开始想的是作战系统的蓝图。我是python新手,我不确定自己是否能够做到这一点。非常感谢。谢谢你这帮了大忙,我不确定我是否能做到。因为我对python还不熟悉,但这帮了我很大的忙,我很高兴我能帮上忙。您可以检查此项以了解更多有关Python中面向对象编程的信息!谢谢你,这很有帮助!
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.