简体   繁体   English

你如何相互依赖处理同一模块中的多个Python类?

[英]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.

相关问题 在python中,您如何处理域名中的其他编码 - In python how do you deal with other encodings in domain names Python - 如何在同一个文件中定义相互依赖的类? - Python - How do I get classes that rely on each other to be defined in the same file? 如何使用具有相同名称且相互依赖的方法处理python继承? - How to deal with python inheritance with methods that have same names and depend each other? 您可以在多个类中导入相同的模块(Python 中接受的约定是什么)? - Can you import the same module in multiple classes (What is the accepted convention in Python)? Python如何继承多个类的属性? - How do you inherit the attributes of multiple classes in Python? 在python中,如何在不保留导入模块名称空间的情况下从其他模块导入所有类? - In python, how do you import all classes from another module without keeping the imported module's namespace? 如何在Python的同一模块目录中导入其他功能? - How do I import other functions in same module directory in Python? 如何确定类不相等 - How to determine that classes do not equal each other Python通过多个其他模块重用同一模块 - Python reuse the same module by multiple other modules Python:如何合并Python类? - Python : How do you merge Python classes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM