我如何评估对象的类值,反之亦然?

时间:2015-09-27 02:56:56

标签: python class

我是一个非常新手的程序员,我最近学习了类试图使一些简单的东西,我想知道如何访问一个类的实例变量到另一个类反之亦然,在代码中我想要的值敌人知道的英雄的健康状况和英雄对敌人所造成的伤害请看评论部分。请帮助我知道我应该尝试自己解决这个问题,但我尝试过没有人帮忙。

class Hero(object):
    def __init__(self,name):
        self.name = name #hero name
        self.health = 100 #hero health
        self.damage = 20 #hero damage
        print "My health now is ",self.health,
    def gethit (self):
        self.health = self.health - 10 #Ten is the Enemy damage value but I don't know how to get from enemy class so put constant
        print"\nOuch my health now is ",self.health

class Enemy(Hero):
    def __init__(self,name):
        self.damage = 10 #enemy damage
        self.name = name #enemy name
        self.health = 100 #enemy name
        print "Bwahahah I know you have ",#want hero health of hero after being hit value of health after gethit function in Hero
mark = Hero("Mark")
mark.gethit()
jake = Enemy("Jake")

1 个答案:

答案 0 :(得分:0)

这不太对。您希望HeroEnemy继承其他类,例如Person(但您现在可以将其保留为普通的Python object类)。现在回答您的问题,mark必须是班级Enemy中的属性(或您引用的字段或类值)。你需要“为每个敌人添加一个英雄”,然后你就能够获得这个英雄的健康状况。看一看!

class Hero(object):
    def __init__(self,name):
        self.name = name #hero name
        self.health = 100 #hero health
        self.damage = 20 #hero damage
        print "My health now is ",self.health,
    def gethit (self):
        self.health = self.health - 10 #Ten is the Enemy damage value but I don't know how to get from enemy class so put constant
        print"\nOuch my health now is ",self.health

class Enemy(object):
    def __init__(self, name, hero):
        self.damage = 10 #enemy damage
        self.name = name #enemy name
        self.health = 100 #enemy name
        self.hero = hero
        print "Bwahahah I know you have " + self.hero.health
mark = Hero("Mark")
mark.gethit()
jake = Enemy("Jake", mark)