我有两个文件,node.py
和path.py
,它们分别定义了两个类,Node
和Path
。
到目前为止,Path
的定义引用了Node
对象,因此我做了
from node.py import *
在path.py
文件中。
然而,截至今天,我为Node
创建了一个引用Path
对象的新方法。
我在尝试导入path.py
时遇到了问题:我试过了,当程序运行并调用使用Path
的Node
方法时,关于Node
未被定义的异常上升。
我该怎么办?
Importing Python Modules是一篇很棒的文章,解释了Python中的循环导入。
解决此问题的最简单方法是将路径导入移动到节点模块的末尾。
另一种方法是仅在您需要的功能中导入两个模块中的一个。当然,如果您只需要一个或少量功能,这种方法效果最好:
# in node.py
from path import Path
class Node
...
# in path.py
class Path
def method_needs_node():
from node import Node
n = Node()
...
我更喜欢通过在另一个依赖类的构造函数中声明其中一个依赖项来打破循环依赖。在我看来,这使代码更整洁,并且可以轻松访问所有需要依赖的方法。
所以在我的情况下,我有一个相互依赖的CustomerService和UserService。我打破循环依赖如下:
class UserService:
def __init__(self):
# Declared in constructor to avoid circular dependency
from server.portal.services.admin.customer_service import CustomerService
self.customer_service = CustomerService()
def create_user(self, customer_id: int) -> User:
# Now easy to access the dependency from any method
customer = self.customer_service.get_by_id(customer_id)