gpt4 book ai didi

python - 类中的循环导入

转载 作者:太空狗 更新时间:2023-10-30 01:11:57 33 4
gpt4 key购买 nike

假设我在两个文件中有两个类:

from Son import Son
class Mother:
def __init__(self):
self.sons = []
def add_son(self, son: Son):
self.sons.append(son)

from Mother import Mother
class Son:
def __init__(self, mother: Mother):
self.mother = mother
mother.add_son(self)

加上一个主文件

from Mother import Mother
from Son import Son
if __name__ == '__main__':
mother = Mother()
son1 = Son(mother)
son2 = Son(mother)

显然,我有一个循环依赖。如何在不丢失类型提示的情况下处理这种行为?

最佳答案

你唯一的循环依赖是在类型提示中,那些可以指定为字符串:

# Mother.py
class Mother:
def __init__(self):
self.sons = []
def add_son(self, son: 'Son.Son'):
self.sons.append(son)

# Son.py
class Son:
def __init__(self, mother: 'Mother.Mother'):
self.mother = mother
mother.add_son(self)

您可能仍然需要import Motherimport Son;我不确定当前的分析工具是否足够智能以解决类型提示问题。 不要使用from 导入;这些在导入时强制解析模块内容。

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

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