gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:55:38 35 4
gpt4 key购买 nike

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

目录如下所示:

/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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com