Python的类的前向声明 [英] Foward declaration of classes in Python

查看:299
本文介绍了Python的类的前向声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序可以成功运行:

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

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

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?

谢谢。

PS。我已经阅读了一些与转发声明相关的答案,但找不到针对我特定问题的答案。

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

推荐答案

在调用这些方法之前,需要使用大量引用,此处可以使用循环导入 。诀窍是使用完全合格的引用。

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

这篇关于Python的类的前向声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆