gpt4 book ai didi

python-3.x - python3中的循环导入

转载 作者:行者123 更新时间:2023-12-03 17:28:17 25 4
gpt4 key购买 nike

我有一个包含几个文件的包。每个文件都包含一个类,并且这些类是相互依赖的。如何在不将所有代码放在一个文件中的情况下避免循环依赖。有没有更好的方法来重构代码或者有没有办法解决循环导入

这是目录结构

.
|-- Complainant.py
|-- Complaint.py
`-- __init__.py

投诉.py:
from .Complainant import Complainant

class Complaint(BaseDocument):
ALL_STATUS = ["waiting","resolved", "rejected"]
text = TextField()
timestamp = DateTimeField()
status = TextField()
complainant_id = TextField()
department_ids = ListField(TextField())

def get_complainant(self):
db = DBManager.db()
complainant = Complainant.load(db, self.complainant_id)
return complainant

投诉人.py
from .Complaint import Complaint

class Complainant(BaseDocument):
account_type = TextField()
account_handle = TextField()
complaint_ids = ListField(TextField())

def get_complaints(self):
db = DBManager.db()
complaints = [Complaint.load(db, i) for i in self.complaint_ids]
return complaints

初始化 .py
from .Complaint import Complaint
from .Complainant import Complainant

__all__ = [
Complaint,
Complainant
]

最佳答案

在具有循环依赖的系统中,为了避免循环导入,您通常必须将相互依赖的部分放在同一个模块中。

在您的情况下,只有一小部分类 ComplaintComplainant是相互依存的。您可以重构模块以将非相互依赖的部分放入 BaseComplaint.py 中的类中。和 BaseComplainant.py ,并使用第三个模块来定义子类ComplaintComplainant .

目录结构:

.
|-- BaseComplainant.py
|-- BaseComplaint.py
|-- ComplaintComplainant.py
`-- __init__.py

BaseComplaint.py:
class BaseComplaint(BaseDocument):
ALL_STATUS = ["waiting","resolved", "rejected"]
text = TextField()
timestamp = DateTimeField()
status = TextField()
complainant_id = TextField()
department_ids = ListField(TextField())

BaseComplainant.py
class BaseComplainant(BaseDocument):
account_type = TextField()
account_handle = TextField()
complaint_ids = ListField(TextField())

ComplaintComplainant.py(也许你能找到更好的名字)
from .BaseComplaint import BaseComplaint
from .BaseComplainant import BaseComplainant

class Complaint(BaseComplaint):
def get_complainant(self):
db = DBManager.db()
complainant = Complainant.load(db, self.complainant_id)
return complainant

class Complainant(BaseComplainant):
def get_complaints(self):
db = DBManager.db()
complaints = [Complaint.load(db, i) for i in self.complaint_ids]
return complaints

初始化文件
from .ComplaintComplainant import Complaint, Complainant

__all__ = [
Complaint,
Complainant
]

关于python-3.x - python3中的循环导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39850696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com