使用安装到父类的模块方法

时间:2014-11-28 11:22:31

标签: python inheritance methods

我有一个包含类层次结构的项目:Unit< - SpellCaster< - Necromancer。在我的Unit我尝试import模块Observers.Observe

from Point import Point
from Observer.Observe import Observerable
from Observer.Observe import Observer
import Excep

import sys

class Unit(object):
    # __slots__ = ['_x', '_y']

    def __init__(self, name, hitpoints, damage, armor=0, location=Point(0, 0)):
        self._name = name
        self._hitpoints = hitpoints
        self._damage = damage
        self._hitpointslimit = hitpoints
        self._armor = armor
        self._location = location

    def ensureisalive(self):
        if self._hitpoints == 0:
            raise UnitIsDeadException()
    blablabla

我的班级Necromancer继承自SpellCaster,继承自Unit

from SpellCasters.SpellCaster import SpellCaster
from Units.Point import Point
from Spells.FireBall import FireBall

class Necromancer(SpellCaster):

    def __init__(self, name, hp, dmg, armor, location, mana):
        super(Necromancer, self).__init__(name, hp, dmg, armor, location, mana)
        self._spell = FireBall()

    def cast(self, target):
        Observer.addobservable(target) # problem is here
        super(Necromancer, self).manaspend(self._spell.cost)
        self._spell.action(target)


    def takedamage(self, dmg):
        super(SpellCaster, self).ensureisalive()
        if dmg > self._hitpoints:
            hitpoints = 0
            Observer.notify()
            return

        self._hitpoints -= dmg


    def __del__(self):
        pass

Necromancer中,我尝试使用Unit中导入的模块中的方法(测试评论)。我得到一个错误,python无法识别Observer。所以我的问题是:如何使用父类中导入的模块中的方法?

1 个答案:

答案 0 :(得分:0)

您不能使用在不同模块中导入的名称,即使这是父模块的命名空间。

直接导入您需要的名称;例如对于具有Observable类的模块,再次导入Necromancer

导入有两件事:

  1. 如果之前没有加载模块,它会加载模块。
  2. 它会在您的命名空间中为导入的对象添加一个引用。
  3. 在两个不同的位置导入相同的模块意味着它只会加载一次,但在您的情况下,您确实希望在包含{{1的模块中创建对Observable类的额外引用}。class。