简体   繁体   English

python类之间的循环依赖

[英]Circular dependency between python classes

In python, class definitions could depend on each other like this:在 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()
  1. Why does clases have this problem, while functions don't?为什么类有这个问题,而函数没有?
  2. Languages like C++ have declarations: class B to resolve this kind of dependency, does python have similar constructs?像 C++ 这样的语言有声明: class B来解决这种依赖,python 有类似的构造吗?

In the function case, we don't actually have to call FuncB to define FuncA.在函数情况下,我们实际上不必调用 FuncB 来定义 FuncA。 FuncB only needs to be called when we actually call FuncA.只有在我们实际调用 FuncA 时才需要调用 FuncB。

Unlike with functions, the body of a class is executed at definition time.与函数不同,类的主体在定义时执行。 To define class A, we need to actually call a B method, which we can't do because class B isn't defined yet.要定义类 A,我们需要实际调用 B 方法,我们不能这样做,因为类 B 尚未定义。

To work around this, we can define the classes and then add the properties afterward:为了解决这个问题,我们可以定义类,然后添加属性:

class A(object):
    ...

class B(object):
    ...

A.b = B.do_sth()
B.A = A.do_sth()

If each do_sth call relies on the other call already having been executed, though, this resolution won't work.但是,如果每个do_sth调用都依赖于已经执行的另一个调用,则此解决方案将不起作用。 You will need to perform more extensive changes to fix the problem.您将需要执行更广泛的更改来解决问题。

  1. Classes have these problems because directives on the class level ( b = B.do_smth() ) are executed while defining the class, not when you create an instance of the class类有这些问题,因为类级别上的指令 ( b = B.do_smth() ) 是在定义类时执行的,而不是在创建类的实例时执行
  2. You may complete the definition of a class lately, after both classes are defined.在定义了两个类之后,您可以在最近完成一个类的定义。 Python is a dynamic language after all. Python毕竟是一种动态语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM