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

2024-06-01 04:12:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: thenameselfifobjectdefrandomelse
3条回答

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

2)您可以使用static variables使它们成为Dragon类本身的一部分。然后可以访问变量,而无需创建类的实例。在

显然,在你这个“龙与游骑兵的世界”这个例子中,第二个解决方案并不是最好的。在

我希望它看起来像:

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合规性。)

我想你想要的是指定被射杀的龙。然后你可以在你的类中传递一个龙的实例。在

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

相关问题 更多 >