python导入错误,似乎是递归导入,但无法通过这种方式解决

时间:2012-03-30 10:16:41

标签: python recursion import mongoengine

已更新问题已解决,我在这里遇到了一些设计问题。

目录看起来像这样:

/view
  |-__init__.py
  |-quiz.py
  |-test.py
  |-user.py

问题在于quiz.py,我从class导入test。在test.py中,我从class导入quiz

更新:我更改了import,但仍有AttributeError

代码如下:

quiz.py

#ignore some imports here
import test
from user import User

class Quiz(Document):
    creator         =   ReferenceField(User, reverse_delete_rule=CASCADE)
    info            =   GenericEmbeddedDocumentField("QuizInfo")
    description     =   StringField(max_length=100)
    attachment      =   GenericEmbeddedDocumentField("QuizAttach")
    correctanswer   =   GenericEmbeddedDocumentField("QuizAnswer")
    wronganswer     =   GenericEmbeddedDocumentField("QuizAnswer")
    manualdifficulty=   FloatField(min_value=0, max_value=1)
    autodifficulty  =   FloatField(min_value=0, max_value=1)
    checkout        =   GenericEmbeddedDocumentField("QuizCheckcout")
    tag             =   ListField(StringField(max_length=20))

#ignore some codes here

class QuizCheckout(EmbeddedDocument):
    time            =   DateTimeField()
    type            =   IntField()
    description     =   StringField()
    test            =   ReferenceField(test.Test, reverse_delete_rule=CASCADE)

test.py

import quiz


class Test(Document):
    createdate      =   DateTimeField()             #Create datetime
    description     =   StringField()               #decription of this test
    takennumber     =   IntField()                  #the number of students who may take this test
    quiz            =   GenericEmbeddedDocumentField('TestQuiz')

class TestQuiz(EmbeddedDocument):
    quiz            =   ListField(ReferenceField(quiz.Quiz, reverse_delete_rule=CASCADE))
                        #Reference to Quiz, if Quiz is deleted, this reference will be deleted too.
    correct         =   IntField()
                        #how many students got this right

,错误是

Exception Type: AttributeError Exception
Value: 'module' object has no attribute 'Quiz'

起初我认为这可能是一个递归问题,但我只发现我可以将import移动到函数中以避免递归导入,但这里没有函数,我试图移动import进入课堂,它不起作用。

有没有办法将这些定义保存在单独的文件中?

3 个答案:

答案 0 :(得分:3)

这是一种经典的循环导入情况。您可以简单地“导入测试”,然后通过test.Test访问Test,而不是使用“来自测试导入测试”。有关详细信息,请参阅此stackoverflow question

答案 1 :(得分:1)

将QuizCheckout移至单独的模块。 (QuizCheckout在类定义级别引用Test,测试引用Quiz,这是问题的根源)

答案 2 :(得分:0)

如果hymloth写的是正确的(我没有尝试过),你也应该能够再次使用名称“Test”:

import test
Test = test.Test