如何在python中使用来自另一个类的变量?

时间:2014-11-12 22:26:53

标签: python class variables

如何从另一个未继承的类中访问变量?在我的代码中,我尝试使用hitPoints方法中的Dragon对象从Ranger对象访问quickShot类变量。

class Dragon(object):
    name = "Dragon"
    hitPoints = 25

# Create the Ranger class
class Ranger(object):
    name = "Ranger"
    attack = 80
    defence = 50
    hitPoints = 100

    def __init__(self):
        self = self

    def quickShot(self):
        damage = 25
        test = random.random()
        if test < .8:
            #I cannot access the dragon's hitPoints
            Dragon.hitPoints = Dragon.hitPoints - damage
        else:
            pass

    def concentratedShot(self):
        damage = 50
        chance = random.random()
        if chance <= .5:
            chance = True
        else:
            chance = False

    def heartSeeker(self):
        damage = 100
        chance = random.random()
        if chance <= .3:
            chance = True
        else:
            chance = False

3 个答案:

答案 0 :(得分:3)

我希望它看起来像:

class Character(object):

    """All Characters have a name and some hit points."""

    def __init__(self, name, hit_points):
        self.name = name # assigned in __init__ so instance attribute
        self.hit_points = hit_points


class Player(Character):

    """Players are Characters, with added attack and defence attributes."""

    def __init__(self, name, hit_points, attack, defence):
        super(Player, self).__init__(name, hit_points) # call superclass
        self.attack = attack
        self.defence = defence

    def _attack(self, other, chance, damage):
        """Generic attack function to reduce duplication."""
        if random.random() <= chance:
            other.hit_points -= damage # works for any Character or subclass

    def quick_attack(self, other):
        """Attack with 80% chance of doing 10 damage."""
        self._attack(other, 0.8, 10)


dragon = Character("Dragon", 25) # dragon is a Character instance
ranger = Player("Ranger", 100, 80, 50) # ranger is a Player instance
ranger.quick_attack(dragon)
print dragon.hit_points

通过这种方式,确保您了解发生了什么以及为什么,然后在此基础上进行构建。如果你不能遵循它,我建议你寻找Python OOP教程(或the official docs);你现在拥有的东西会让你无处可去。

(请注意style guide合规奖励。)

答案 1 :(得分:0)

我认为你想要的是指定正在射击的龙。然后你可以在你的班级传递一个龙的实例。

def quickShot(self, dragon):
    damage = 25
    test = random.random()
    if test < .8:
        dragon.hitPoints -= damage
    else:
        pass

答案 2 :(得分:0)

1)您需要创建 Dragon 类的实例并将其传递给 def quickShot(self):方法

2)您可以使用static variables使其成为 Dragon 类本身的一部分。然后,您可以在不创建类的实例的情况下访问变量。

显然,在你的特殊情况下&#34;充满龙与流浪者的世界&#34;第二种解决方案并不是最好的解决方案。