1

I have many derived classes of foo class and I am trying to instantiate object of base class to one of derived classes. I want to call constructor of base class only once. I am getting runtime error while I am trying to execute following piece of code:

class foo():
     call_once = True
     _Bar = None
     _BaseClass = None
     def __init__(self):
           if (self.call_once):
               self.call_once = False
               self._Bar = bar()
               self._BaseClass = _bar

class bar(foo):
     def __init__(self):
           foo.__init__(self)

bar1 = bar()
6
  • This doesn't make any sense. What's the point of having foo instances that aren't initialized? Why is the first one special? Whatever you're doing, I guarantee there's a better way to do it. Commented Jun 12, 2017 at 7:32
  • please suggest better way. I have written in a question what am I trying to do. Commented Jun 12, 2017 at 7:35
  • So foo() instantiates an object of type bar. But bar() calls the __init__ method of foo(), which in turn instantiates an object of type bar. This results in an infinite loop. The if statement does not help here, since the recursion occurs within the ifblock. Commented Jun 12, 2017 at 7:35
  • No, the better way is to not make a class that only executes its constructor once. The question is, why do you think this is the way to solve your problem (whatever it is)? If you don't tell us why you want to avoid calling the constructor, we can't offer any better alternatives. Commented Jun 12, 2017 at 7:38
  • I don't think that recursion is occurring in if block because I am calling init method of foo which should check call_once and if it is false it should not loop again Commented Jun 12, 2017 at 7:38

1 Answer 1

2

This happens because call_once is a class variable but you are assigning False to the call_once instance variable. To fix it, check and assign False to foo.call_once.

class foo():
     call_once = True
     _Bar = None
     _BaseClass = None
     def __init__(self):
           if (foo.call_once):
               foo.call_once = False
               self._Bar = bar()
               self._BaseClass = _bar
Sign up to request clarification or add additional context in comments.

1 Comment

Worked! Thanks a lot for helping me out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.