已更新 问题已解决,我这里有一些设计问题。
目录如下所示:
/view
|-__init__.py
|-quiz.py
|-test.py
|-user.py
问题是在 quiz.py
中,我从 test
导入了一个 class
。在 test.py
中,我从 quiz
导入了一个 class
。
更新:我更改了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)
测试.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
到类中,它不起作用。
有没有办法将这些定义保存在单独的文件中?
最佳答案
这是典型的循环导入情况。您可以简单地“导入测试”,然后通过 test.Test 访问测试,而不是使用“from test import Test”。有关详细信息,请参阅此 stackoverflow question .
关于python导入错误,好像是递归导入,但无法通过这种方式解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9941083/