[英]How do you deal with multiple Python classes in the same module depending on each other?
I'm using an ODM library and I'm defining documents as classes within the same module, when they are related. 我正在使用ODM库,并且当它们相关时,我将文档定义为同一模块中的类。 I've hit a circular dependency problem and because I haven't come across this before in Python, I don't know how to inform the classes of the existence of each other. 我遇到了一个循环依赖问题,因为我之前在Python中没有遇到过这个问题,我不知道如何告知类别彼此的存在。 Example: 例:
''' docs.py '''
from mongoengine import Document
from mongoengine.fields import StringField, ReferenceField, ListField
class Base(Document):
some_field = StringField()
class Foo(Base):
other_field = StringField()
another_field = ReferenceField(Bar)
class Bar(Base):
other_field = StringField()
another_field = ListField(ReferenceField(Foo))
As it stands the Python will throw a NameError
because Bar
is not defined when the interpreter gets to a reference to it in the file, within the class Foo
. 就目前而言,Python将抛出一个NameError
因为当解释器在类Foo
中获取文件中的引用时,不会定义Bar
。 How do I tell Python not to worry and that the class definition will be along shortly? 我如何告诉Python不要担心,并且类定义将很快出现?
ReferenceField
接受类名。
another_field = ReferenceField('Bar')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.