简体   繁体   中英

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.

The thing to watch out for is

First = Second
  • Because of the assignment, First() will create an instance of class Second
  • Second.__init__() will call First.__init__() .
  • in First.__init__() , First will be looked up by name in the global context.
  • Since you reassigned First = Second , the name First points to class Second . Which will get its __init__() called and that gives you your infinite recursion.

In short: Don't do this ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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