Skip to content

Instantly share code, notes, and snippets.

@valsteen
Last active December 31, 2015 09:09
Show Gist options
  • Select an option

  • Save valsteen/7965309 to your computer and use it in GitHub Desktop.

Select an option

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
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