我有一个包含类层次结构的项目: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。所以我的问题是:如何使用父类中导入的模块中的方法?
答案 0 :(得分:0)
您不能使用在不同模块中导入的名称,即使这是父模块的命名空间。
直接导入您需要的名称;例如对于具有Observable
类的模块,再次导入Necromancer
。
导入有两件事:
在两个不同的位置导入相同的模块意味着它只会加载一次,但在您的情况下,您确实希望在包含{{1的模块中创建对Observable
类的额外引用}。class。