4

This is my first post, so first of all I want to say a giant "Thank you!" to the community of stackoverflow for all the time an answer did the trick for me :)

I have a problem while dealing with python's inheritance.

I have a parent class which contains the following code:

def start(self):

  pid = os.fork()

  if (pid==0):
   self.__do_in_forked_process()
  elif(pid > 0):
   self.__do_in_parent_process()
  else:
   print ("Error while forking...")
   sys.exit(1)

The __do_in_forked_process() method contains a method self.__manage_request() which is defined in the parent class and overridden in the child class.

In the child class, when I use use the method self.start() the problem arise: the self.__manage_request() method executed is the one defined in the parent class instead of the method define in the child class (even if, I suppose, when I do self.start() the start method and all the things inside it should refer to the child object instead of to the parent object).

Thanks in advance!

turkishweb

1 Answer 1

7

Don't use TWO leading underscores in your method and other attribute names: they're specifically intended to isolate parent classes from subclasses, which is most definitely what you do not want here! Rename the method in question to _manage_request (single leading underscore) throughout, and live happily ever after. And in the future use double leading underscores only when you're absolutely certain you never want any override (or acess from subclass methods) of that attribute (method being just a special case of attribute).

In C++ terminology, single leading underscore means protected: subclasses are allowed and welcome to access and override. Double leading underscores mean private: meant to be hands-off even for subclasses (and with some compiler name mangling to help it be so). Rarely have I seem double leading underscores used with clear purpose and understanding of this.

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

1 Comment

You're lucky. Your first question was answered by one of the most prominent python experts in the world.

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.