Python类继承和super()行为?

时间:2016-04-19 19:59:31

标签: python class inheritance super

我试图在python中自学有关super()和类继承的失败。鉴于以下代码,有人可以告诉我为什么我期望发生...不是吗?

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

for i in enemy_list:
    print "(", i.lvl, i.name, i.attack_power, i.health, ")"

为什么输出此代码:

( 2 <__main__.Enemy object at 0x7faa040b3050> 0.1 80 )
( 5 <__main__.Enemy object at 0x7faa040b30d0> 0.25 200 )
( 3 <__main__.Enemy object at 0x7faa040b3150> 0.15 120 )
( 5 <__main__.Enemy object at 0x7faa040b31d0> 0.25 200 )

而不是预期的:

( 2 goblin 0.1 80 )
( 5 goblin 0.25 200 )
( 3 goblin 0.15 120 )
( 5 goblin 0.25 200 )

3 个答案:

答案 0 :(得分:1)

此行传入enemy

enemy_list.append(Enemy(enemy, player))

也许你想要这样的东西:

def createEnemy(enemy_name):
    enemy_list.append(Enemy(enemy_name, player))
    return enemy_list

while enemy_amount > 0:
    createEnemy("goblin", player)
    enemy_amount -= 1

答案 1 :(得分:1)

你没有传递name的字符串,而是传递敌人的对象。执行顺序是:

createEnemy(Enemy("goblin", player))

然后

enemy_list.append(Enemy(enemy, player))

然后

super(Enemy, self).__init__(name)

此时name不是字符串而是敌方对象。

答案 2 :(得分:0)

您正在传递一个Enemy对象作为名称

def createEnemy(enemy):
    enemy_list.append(Enemy(enemy, player))
    return enemy_list


createEnemy(Enemy("goblin", player))

您拨打createEnemy,传递Enemy。在createEnemy内,您将该敌人对象作为第一个参数传递,以创建另一个Enemy(第一个参数应该是名称)。