铅与圆形进口

时间:2014-10-06 07:04:33

标签: python

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

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

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" 

Class Cat

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)

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

谢谢,

菲利普

1 个答案:

答案 0 :(得分:0)

这里没有发生循环导入。

问题是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)
相关问题