【问题标题】:Pb with circular imports循环进口铅
【发布时间】:2014-10-06 07:04:33
【问题描述】:

我有这四个描述世界的类,有猫和老鼠,只有一个动物中的方法来搜索特定的动物(猫或老鼠)。

单个文件中的所有代码都有效(打印:“我是鼠标”)但如果我将每个文件拆分一个类,我会收到以下错误消息:

if isinstance(ani,getattr(sys.modules[__name__],className)):
AttributeError: 'module' object has no attribute 'Mouse'

类动物

import sys

class Animal(object):

def searchAnimal(self,animals,className):
    theAnimal = None              
    for ani in animals:
        if isinstance(ani,getattr(sys.modules[__name__],className)): 
            theAnimal = ani    
    return theAnimal

类鼠标

from Animal import * 

class Mouse(Animal):

    def __str__(self):
        return "I'm a mouse" 

类猫

from Animal import *

class Cat(Animal):

    def __str__(self):
        return "I'm a cat" 

班级世界

from Cat import *
from Mouse import *

class World(object):

    def __init__(self):
        self.animals = []  
        for i in range(0,2):   # 2 Cats
            self.animals.append(Cat())
        for i in range(0,5):  # and 5 Mice
            self.animals.append(Mouse())            

if __name__ == '__main__':
    aWorld = World()
    theCat = aWorld.animals[0]
    ani = theCat.searchAnimal(aWorld.animals,"Mouse")
    print(ani)

我该如何解决这个问题?这可能是由于循环导入。

谢谢,

菲利普

【问题讨论】:

  • 您似乎正在尝试使用一种复杂的方式来解决此问题。你能解释一下你想要实现/设计的目标吗?

标签: python


【解决方案1】:

这里没有循环导入。

问题是sys.modules[__name__] 将返回调用函数的模块。在您的情况下,模块将是module animal。没有Mouse的类定义

当你在同一个模块中定义了所有类时,sys.modules[__name__] 将返回同一个模块并且它会工作。

更好的方法是将动物的类型存储在类中(在初始化期间)

animal.py

class Animal(object):
    def __init__(self):
        self.type = None

    def searchAnimal(self,animals,aniType):
        theAnimal = None
        for ani in animals:
            if ani.type == aniType:
                theAnimal = ani
        return theAnimal

cat.py

from animal import *

class Cat(Animal):
    def __init__(self):
        self.type = 'cat'
    def __str__(self):
        return "I'm a cat"

mouse.py

from animal import *

class Mouse(Animal):
    def __init__(self):
        self.type = 'mouse'
    def __str__(self):
        return "I'm a mouse"

world.py

from cat import *
from mouse import *

class World(object):

    def __init__(self):
        self.animals = []
        for i in range(0,2):   # 2 Cats
            self.animals.append(Cat())
        for i in range(0,5):  # and 5 Mice
            self.animals.append(Mouse())

if __name__ == '__main__':
    aWorld = World()
    theCat = aWorld.animals[0]
    ani = theCat.searchAnimal(aWorld.animals,"mouse")
    print(ani)

【讨论】:

  • 谢谢。有用。很抱歉,我不能投票,因为我没有足够的声望。
  • 在我的程序的第一个版本中,我使用: if isinstance(ani,eval(className)): 而不是 if isinstance(ani,getattr(sys.modules[name],className)): 但它也不起作用。和你描述的问题一样吗?
  • 是的,当您执行eval(expr) 时,python 会尝试评估当前namespace 中的表达式。因为该命名空间中不存在“鼠标”,所以它会抛出 NameError。
猜你喜欢
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-19
相关资源
最近更新 更多