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

查看:161
本文介绍了如何避免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.

更具体地说,一个类是可变的,一个是不可变的。不可变类需要
进行散列,比较等等。可变类也需要做事。这与sets和frozensets或者列表和元组类似。

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天全站免登陆