Skip to content

Instantly share code, notes, and snippets.

@gjcourt
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gjcourt/99b1e1b5d7c3b0c72b79 to your computer and use it in GitHub Desktop.
Save gjcourt/99b1e1b5d7c3b0c72b79 to your computer and use it in GitHub Desktop.
Name Mangling example.
class Foo(object):
def __init__(self, **kwargs):
self.__attr = kwargs.pop('attr', None)
@property
def bar(self):
return self.__attr
def test_foo():
foo = Foo()
assert hasattr(foo, '_Foo__attr')
assert foo._Foo__attr is None
def test_foo_custom_attr():
foo = Foo(attr='bar')
assert hasattr(foo, '_Foo__attr')
assert foo._Foo__attr == 'bar'
def test_foo_bar():
foo = Foo()
assert foo.bar is None
def test_foo_bar_custom_attr():
foo = Foo(attr='bar')
assert foo.bar == 'bar'
if __name__ == '__main__':
"""
Name mangling of double underscore attributes.
tl;dr __attr attributes are class private.
For more background see http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python
"""
test_foo()
test_foo_custom_attr()
test_foo_bar()
test_foo_bar_custom_attr()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment