Name Mangling of Python Private Variables


/ Published in: Python
Save to your folder(s)

Python: Private Variables
http://docs.python.org/tut/node11.html#SECTION0011600000000000000000

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

Truncation may occur when the mangled name would be longer than 255 characters. When the class name consists of only underscores, no mangling occurs.


Copy this code and paste it in your HTML
  1. def _mangle_name(self, name):
  2. """
  3. Any identifier of the form __spam (at least two leading underscores,
  4. at most one trailing underscore) is textually replaced with
  5. _classname__spam, where classname is the current class name with
  6. leading underscore(s) stripped.
  7.  
  8. Truncation may occur when the mangled name would be longer than
  9. 255 characters. When the class name consists of only underscores,
  10. no mangling occurs.
  11. """
  12.  
  13. klass = self.__class__.__name__
  14. if name.startswith("__") and not name.endswith("__"):
  15. import re
  16. if not re.compile(r"^_+$").match(klass):
  17. # NOTE: In Python 2.5, no trunction occurred?
  18. #name = ("_%s%s" % (klass, name))[0:255]
  19. name = ("_%s%s" % (klass, name))
  20. return name

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.