Python 中类的前向声明

发布于 2024-10-08 05:46:28 字数 1309 浏览 3 评论 0原文

以下程序可以成功运行:

class Simple(object):
    def __init__(self, name):
      self.name = name

    def __add__(self, other):
      c = Composite()
      c._members.append(self)
      c._members.append(other)
      return c

    def __repr__(self):
      return "Simple('%s')" % self.name

class Composite(object):
    def __init__(self):
      self._members = []

    def __add__(self, obj):
      if isinstance(obj, Simple):
        out = Composite()
        out._members = [k for k in self._members] + [obj]
      elif isinstance(obj, Composite):
        out = Composite()
        out._members = [k for k in self._members + obj._members]
      else:
        raise TypeError
      return out

if __name__ == "__main__":
    s1 = Simple('one')
    s2 = Simple('two')
    s3 = Simple('three')
    c1 = s1 + s2
    c2 = c1 + s3
    print c1._members
    print c2._members
    # output:
    # [Simple('one'), Simple('two')]
    # [Simple('one'), Simple('two'), Simple('three')]

我想将 SimpleComposite__main__ 的定义保留在三个不同的文件中,但我不能这样做是因为我无法将 Simple 导入到 composite.py 中,并且无法将 Composite 导入到 simple.py 中。

您将如何修改类定义以便可以保留单独的文件?

谢谢。

附言。我已经阅读了几个与“前向声明”相关的答案,但找不到我的具体问题的答案。

The following program can run successfully:

class Simple(object):
    def __init__(self, name):
      self.name = name

    def __add__(self, other):
      c = Composite()
      c._members.append(self)
      c._members.append(other)
      return c

    def __repr__(self):
      return "Simple('%s')" % self.name

class Composite(object):
    def __init__(self):
      self._members = []

    def __add__(self, obj):
      if isinstance(obj, Simple):
        out = Composite()
        out._members = [k for k in self._members] + [obj]
      elif isinstance(obj, Composite):
        out = Composite()
        out._members = [k for k in self._members + obj._members]
      else:
        raise TypeError
      return out

if __name__ == "__main__":
    s1 = Simple('one')
    s2 = Simple('two')
    s3 = Simple('three')
    c1 = s1 + s2
    c2 = c1 + s3
    print c1._members
    print c2._members
    # output:
    # [Simple('one'), Simple('two')]
    # [Simple('one'), Simple('two'), Simple('three')]

I would like to keep the definition of Simple, Composite, and __main__ in three different files, but I cannot do it because I cannot import Simple into composite.py and I cannot import Composite into simple.py.

How would you modify the class definition such that you can keep separate files?

Thank you.

PS. I've read several answers related to "forward declaration" but could not find an answer to my specific problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱的十字路口 2024-10-15 05:46:28

由于在调用方法之前不需要任何引用,因此循环导入可以在这里工作。诀窍是使用完全限定的引用。

import composite

class Simple(object):
   ...
  def __add__(self, other):
    c = composite.Composite()
    c._members.append(self)
    c._members.append(other)
    return c

Since none of the references are needed until the methods are called, circular imports can work here. The trick is to use fully-qualified references.

import composite

class Simple(object):
   ...
  def __add__(self, other):
    c = composite.Composite()
    c._members.append(self)
    c._members.append(other)
    return c
何以心动 2024-10-15 05:46:28

问题是你得到了循环导入,对吧?

import Simple 在 __add__ 方法中而不是在文件顶部,以避免循环依赖。它会稍微减慢 __add__ 方法的速度,但通常不会很明显。

The problem is that you get circular imports, right?

import Simple in the __add__ method instead of at the top of the file to avoid circular dependency. It will slow down the __add__ method somewhat, but usually not significantly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文