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

2024-10-03 09:08:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有类层次结构的项目: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中导入的模块中的方法(test被注释)。我遇到了一个python无法识别的错误。所以我的问题是:如何使用从父类中导入的模块的方法


Tags: 模块namefromimportselfdefunitlocation
1条回答
网友
1楼 · 发布于 2024-10-03 09:08:33

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

直接导入你需要的名字;e、 g.为带有Necromancer类的模块再次导入Observable

导入有两件事:

  1. 如果以前没有加载模块,它将加载该模块
  2. 它将命名空间中的引用添加到导入的对象

在两个不同的位置导入同一个模块意味着只加载一次,但是在您的情况下,您确实希望在包含Necromancer类的模块中创建对Observable类的额外引用

相关问题 更多 >