python类之间的循环依赖

Neo*_*ang 7 python

在python中,类定义可能依赖于彼此:

 # This is not fine
 class A():
     b = B().do_sth();
     def do_sth(self):
         pass

 class B():
     a = A().do_sth();
     def do_sth(self):
         pass

 # This is fine
 def FuncA():
     b = FuncB()

 def FuncB():
     a = FuncA()
Run Code Online (Sandbox Code Playgroud)
  1. 为什么clases有这个问题,而函数没有?
  2. 像C++这样的语言有声明:class B要解决这种依赖,python是否有类似的结构?

use*_*ica 10

在函数的情况下,我们实际上不必调用FuncB来定义FuncA.当我们实际调用FuncA时,只需要调用FuncB.

与函数不同,类的主体在定义时执行.要定义类A,我们需要实际调用一个B方法,我们不能这样做,因为类B尚未定义.

要解决这个问题,我们可以定义类,然后添加属性:

class A(object):
    ...

class B(object):
    ...

A.b = B.do_sth()
B.A = A.do_sth()
Run Code Online (Sandbox Code Playgroud)

但是,如果每次do_sth调用都依赖于已执行的另一个调用,则此解决方案将不起作用.您需要执行更广泛的更改才能解决问题.