0

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?

1
  • tag your programming language Commented Mar 2, 2015 at 10:19

1 Answer 1

2

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 ...

Sign up to request clarification or add additional context in comments.

2 Comments

instead of super() if I call parent constructor directly, it does not go into recursive loop.. however my purpose is to patch the original function runtime and not the class itself. Monkey patching kind of approach might help.
Helper tools for function/method wrapping and monkey patching are in functools, functools.wraps is your friend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.