Last active
December 31, 2015 09:09
-
-
Save valsteen/7965309 to your computer and use it in GitHub Desktop.
Demonstration of private variables, one using name mangling of attributes prepended by a double underscore, and using a closure like in javascript
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
| def myclass_factory(): | |
| """ | |
| Run this test with nosetests --with-doctest myclass.py | |
| >>> myclass = myclass_factory() | |
| >>> myclass.__private_attribute | |
| Traceback (most recent call last): | |
| ... | |
| AttributeError: 'MyClass' object has no attribute '__private_attribute' | |
| >>> myclass2 = myclass_factory() | |
| >>> myclass.push(1) | |
| >>> myclass2.push(2) | |
| >>> myclass.pop() | |
| 1 | |
| >>> myclass.pop() | |
| Traceback (most recent call last): | |
| ... | |
| IndexError: pop from empty list | |
| >>> myclass2.pop() | |
| 2 | |
| """ | |
| # this variable is inaccessible, and unique for each call to myclass_factory | |
| private_variable = [] | |
| class MyClass(object): | |
| def __init__(self): | |
| self.__private_attribute = 1 | |
| def push(self, obj): | |
| private_variable.append(obj) | |
| def pop(self): | |
| return private_variable.pop() | |
| return MyClass() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment