Monday 15 February 2010

How can I use variables from another class in python? -



How can I use variables from another class in python? -

how can access variable class not inherited? in code trying access hitpoints class variable dragon object ranger object in quickshot method.

class dragon(object): name = "dragon" hitpoints = 25 # create ranger class class ranger(object): name = "ranger" attack = 80 defence = 50 hitpoints = 100 def __init__(self): self = self def quickshot(self): harm = 25 test = random.random() if test < .8: #i cannot access dragon's hitpoints dragon.hitpoints = dragon.hitpoints - harm else: pass def concentratedshot(self): harm = 50 chance = random.random() if chance <= .5: chance = true else: chance = false def heartseeker(self): harm = 100 chance = random.random() if chance <= .3: chance = true else: chance = false

i expect like:

class character(object): """all characters have name , nail points.""" def __init__(self, name, hit_points): self.name = name # assigned in __init__ instance attribute self.hit_points = hit_points class player(character): """players characters, added attack , defence attributes.""" def __init__(self, name, hit_points, attack, defence): super(player, self).__init__(name, hit_points) # phone call superclass self.attack = attack self.defence = defence def _attack(self, other, chance, damage): """generic attack function cut down duplication.""" if random.random() <= chance: other.hit_points -= harm # works character or subclass def quick_attack(self, other): """attack 80% chance of doing 10 damage.""" self._attack(other, 0.8, 10) dragon = character("dragon", 25) # dragon character instance ranger = player("ranger", 100, 80, 50) # ranger player instance ranger.quick_attack(dragon) print dragon.hit_points

work through that, ensure understand what's happening , why, build on it. if can't follow it, suggest python oop tutorial (or the official docs); have fast.

(note bonus style guide compliance.)

python class variables

No comments:

Post a Comment