fork download
  1. import inspect
  2.  
  3. class foo(object):
  4. def publicMethod(self):
  5. print "This is foo's public method, named %s"%(inspect.getframeinfo(inspect.currentframe()).function)
  6. def __privateMethod(self):
  7. print "This is foo's private method, named %s"%(inspect.getframeinfo(inspect.currentframe()).function)
  8. def privateMethodCaller(self):
  9. self.__privateMethod()
  10.  
  11.  
  12. f = foo()
  13. f.publicMethod()
  14. try:
  15. f.__privateMethod()
  16. except:
  17. print "Oops, it's not quite that simple."
  18. print "Attributes whose names start with '__' are mangled to prevent subclasses from accidentally overriding their superclasses' private attributes, like __init__."
  19. print "The good(?) news is, we can still access the so-called private method if we really want to."
  20.  
  21. print dir(f)
  22. print "Private methods' names are mangled by prepending '_className', where 'className' is the name of the class."
  23. getattr(f, '_%s__privateMethod'%(f.__class__.__name__))()
  24. print "Notice that the name is not mangled inside of the class. This means we can use the unmangled name inside of the class definition."
  25. f.privateMethodCaller()
Success #stdin #stdout 0.03s 9376KB
stdin
Standard input is empty
stdout
This is foo's public method, named publicMethod
Oops, it's not quite that simple.
Attributes whose names start with '__' are mangled to prevent subclasses from accidentally overriding their superclasses' private attributes, like __init__.
The good(?) news is, we can still access the so-called private method if we really want to.
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_foo__privateMethod', 'privateMethodCaller', 'publicMethod']
Private methods' names are mangled by prepending '_className', where 'className' is the name of the class.
This is foo's private method, named __privateMethod
Notice that the name is not mangled inside of the class. This means we can use the unmangled name inside of the class definition.
This is foo's private method, named __privateMethod