Python相互依赖的类(循环依赖) [英] Python mutually dependent classes (circular dependencies)
本文介绍了Python相互依赖的类(循环依赖)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我搜索了很多,但我发现主要是在Python中递归编程的例子。所以这里有个问题:
I've searched a lot, but what I find is mainly examples of recursive programming in python. So here goes the question:
如何实现这个?
class A:
b = B()
class B:
a = A()
推荐答案
在Python中,一切都是动态的 - 甚至是类声明。在初始声明之后,没有什么可以阻止您修改类的内容:
Everything is dynamic in Python - even the class declarations. There's nothing to stop you modifying the contents of a class after the initial declaration:
class A:
pass
class B:
a = A()
A.b = B()
注意:如果你不熟悉Python, pass
关键字只是允许你说'什么都不在这里' - 它不重要除非A类与此示例中一样为空!
NB: If you're not that familiar with Python, the pass
keyword simply allows you to say 'nothing here' - it's not important unless class A is as empty as it is in this example!
这篇关于Python相互依赖的类(循环依赖)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文