Python class inheritance and super() behavior? -
i'm attempting teach myself super() , class inheritance in python unsuccessfully. given following code, can tell me why expect happen...isn't?
import random enemy_list = [] class entity(object): def __init__(self, name=''): self.name = name self.health = 1 self.attack_power = .05 class enemy(entity): def __init__(self, name, target): super(enemy, self).__init__(name) self.lvl = random.randint(target.lvl - 2, target.lvl + 2) self.health *= self.lvl * target.health self.attack_power *= self.lvl def createenemy(enemy): enemy_list.append(enemy(enemy, player)) return enemy_list enemy_amount = random.randint(1, 5) while enemy_amount > 0: createenemy(enemy("goblin", player)) enemy_amount -= 1 in enemy_list: print "(", i.lvl, i.name, i.attack_power, i.health, ")"
why code outputting:
( 2 <__main__.enemy object @ 0x7faa040b3050> 0.1 80 ) ( 5 <__main__.enemy object @ 0x7faa040b30d0> 0.25 200 ) ( 3 <__main__.enemy object @ 0x7faa040b3150> 0.15 120 ) ( 5 <__main__.enemy object @ 0x7faa040b31d0> 0.25 200 )
instead of expected:
( 2 goblin 0.1 80 ) ( 5 goblin 0.25 200 ) ( 3 goblin 0.15 120 ) ( 5 goblin 0.25 200 )
the enemy
being passed in on line:
enemy_list.append(enemy(enemy, player))
perhaps want like:
def createenemy(enemy_name): enemy_list.append(enemy(enemy_name, player)) return enemy_list while enemy_amount > 0: createenemy("goblin", player) enemy_amount -= 1
Comments
Post a Comment