简体   繁体   English

Python:构造函数进入无限循环

[英]python: Constructor goes into infinite loop

My purpose is to override some of the functions of 'First' class run-time for certain cases. 我的目的是在某些情况下重写“一流”运行时的某些功能。 So I want to derive a class from the original one. 因此,我想从原始类派生一个类。 Here is the code snippet. 这是代码片段。

class First(object):

    def __init__(self):
        print "First"
        super(First, self).__init__()

    def foo(self):
        print "foo"

class Second(First):

    def __init__(self):
        print "second"
        super(Second, self).__init__()

    def foo(self):
        print "want to override this"

First = Second

o = First()

Why the constructor goes into infinite loop? 为什么构造函数会陷入无限循环? What wrong thing am doing? 错在做什么?

Python names are not looked up at compile time, name lookups happen when the code is executed. 在编译时不查找Python名称,在执行代码时进行名称查找。

The thing to watch out for is 要注意的是

First = Second
  • Because of the assignment, First() will create an instance of class Second 由于分配, First()将创建class Second的实例。
  • Second.__init__() will call First.__init__() . Second.__init__()将调用First.__init__()
  • in First.__init__() , First will be looked up by name in the global context. First.__init__() ,将在全局上下文中按名称查找First
  • Since you reassigned First = Second , the name First points to class Second . 由于您已重新分配First = Second ,因此名称 First指向class Second Which will get its __init__() called and that gives you your infinite recursion. 它将调用其__init__()并为您提供无限递归。

In short: Don't do this ... 简而言之:不要这样做...

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

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