1

更新的问题解决了,我这里有一些设计问题。

该目录如下所示:

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

问题是quiz.py,我classtest. 在 中test.py,我classquiz.

更新:我改变了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移入类,它不起作用。

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

4

3 回答 3

3

这是典型的循环进口情况。您可以简单地“导入测试”,然后通过 test.Test 访问测试,而不是使用“从测试导入测试”。有关更多信息,请参阅此stackoverflow 问题

于 2012-03-30T10:24:55.160 回答
1

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

于 2012-03-30T10:56:47.110 回答
0

如果 hymloth 写的是正确的(我没有尝试过),您还应该能够通过执行以下操作再次使用名称“Test”:

import test
Test = test.Test
于 2012-03-30T10:28:33.723 回答