如何避免 Python 中的循环导入? [英] How to avoid circular imports in Python?

查看:22
本文介绍了如何避免 Python 中的循环导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Python 中的循环导入问题之前已经出现过很多次,并且我已经阅读了这些讨论.在这些讨论中反复出现的评论是循环导入是糟糕设计的标志,应该重新组织代码以避免循环导入.

I know the issue of circular imports in python has come up many times before and I have read these discussions. The comment that is made repeatedly in these discussions is that a circular import is a sign of a bad design and the code should be reorganised to avoid the circular import.

有人能告诉我在这种情况下如何避免循环导入吗?:我有两个类,我希望每个类都有一个构造函数(方法),它采用另一个类的实例并返回该类的一个实例.

Could someone tell me how to avoid a circular import in this situation?: I have two classes and I want each class to have a constructor (method) which takes an instance of the other class and returns an instance of the class.

更具体地说,一类是可变的,一类是不可变的.需要不可变类用于散列、比较等.做事情也需要可变类.这类似于集合和冻结集或列表和元组.

More specifically, one class is mutable and one is immutable. The immutable class is needed for hashing, comparing and so on. The mutable class is needed to do things too. This is similar to sets and frozensets or to lists and tuples.

我可以将两个类定义放在同一个模块中.还有其他建议吗?

I could put both class definitions in the same module. Are there any other suggestions?

一个玩具示例是 A 类,它有一个列表属性,B 类有一个元组属性.然后类 A 有一个方法,它采用类 B 的实例并返回类 A 的实例(通过将元组转换为列表),类似地,类 B 有一个方法,它采用类 A 的实例并返回类 B 的实例(通过将列表转换为元组).

A toy example would be class A which has an attribute which is a list and class B which has an attribute which is a tuple. Then class A has a method which takes an instance of class B and returns an instance of class A (by converting the tuple to a list) and similarly class B has a method which takes an instance of class A and returns an instance of class B (by converting the list to a tuple).

推荐答案

只导入模块,不要从模块导入:

Only import the module, don't import from the module:

考虑a.py:

import b

class A:
    def bar(self):
        return b.B()

b.py:

import a

class B:
    def bar(self):
        return a.A()

这工作得很好.

这篇关于如何避免 Python 中的循环导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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