Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with inheritance and "self" reference

Tags:

python

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

like image 374
turkishweb Avatar asked Sep 07 '25 18:09

turkishweb


1 Answers

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.

like image 55
Alex Martelli Avatar answered Sep 11 '25 05:09

Alex Martelli