0

I stumbled on mangling by accident - I put two underscores instead of one in a class function name - but have found it to be quite useful. For example, I have various objects that need some air traffic control between them so I can call their parent objects with the same function, i.e. parentobject.__remove(). It's not much different to use parentobject._remove_myclass() but I kinda like the mangling!

Mangling seems designed to protect parent class objects from being overridden so is exploiting this a) "pythonic" and more importantly b) reliable/a good idea?

class myClass():

  def __mc_func(self):
    print ('Hello!')

  def _yetAnotherClass__mc_func(self):
    print ('Mangled from yetAnotherClass!')
    
  def new_otherClass(self):
    return otherClass(self)

  def new_yetAnotherClass(self):
    return yetAnotherClass(self)  
 
 
class otherClass():
  def __init__(self, myClass_instance):
    self.mci = myClass_instance
      
  def func(self):
    self.mci.__mc_func()

class yetAnotherClass():
  def __init__(self, myClass_instance):
    self.mci = myClass_instance
      
  def func(self):
    self.mci.__mc_func()

g = myClass()
h = g.new_otherClass()
try:
  h.func()
except AttributeError as e:
  print (e)
  #'myClass' object has no attribute '_otherClass__mc_func'

j = g.new_yetAnotherClass()
j.func()
#Mangled from yetAnotherClass!
  • Does this answer your question? [What is the meaning of single and double underscore before an object name?](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name) – Alex Metsai Feb 17 '21 at 11:50
  • There is a great answer in this thread: https://stackoverflow.com/questions/7456807/python-name-mangling – Jamie Feb 17 '21 at 11:50

0 Answers0