Python的类的前向声明

Python的类的前向声明

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

问题描述

以下程序可以成功运行:

The following program can run successfully:

的定义和 __ 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的类的前向声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 22:27