Last active
August 29, 2015 14:20
-
-
Save gjcourt/99b1e1b5d7c3b0c72b79 to your computer and use it in GitHub Desktop.
Name Mangling example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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