【问题标题】:How do you deal with multiple Python classes in the same module depending on each other?您如何处理同一模块中的多个 Python 类相互依赖?
【发布时间】:2012-01-10 13:32:15
【问题描述】:

我正在使用 ODM 库,并且我将文档定义为同一模块中的类(当它们相关时)。我遇到了一个循环依赖问题,因为我以前在 Python 中没有遇到过这个问题,所以我不知道如何通知类彼此存在。示例:

''' 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))

就目前而言,Python 将抛出一个NameError,因为当解释器在文件中的类Foo 中获取对它的引用时,没有定义Bar。如何告诉 Python 不要担心,类定义很快就会出现?

【问题讨论】:

标签: python class import


【解决方案1】:

ReferenceField 也接受类名。

another_field   = ReferenceField('Bar')

【讨论】:

  • 我不知道(在 API 文档中没有提到),引用 A.field = ReferenceField(B) 的方法可能更适用于 Python,但我认为这种方法在这里更可取,因为它保持模块中的可读性(所有文档字段组合在一起)– Edwardr 9 秒前编辑
猜你喜欢
  • 2021-02-21
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 2013-04-06
  • 1970-01-01
  • 2013-12-09
  • 2012-02-04
相关资源
最近更新 更多