Skip to content

Instantly share code, notes, and snippets.

@jbail
Created November 19, 2010 06:35
Show Gist options
  • Save jbail/706193 to your computer and use it in GitHub Desktop.
Save jbail/706193 to your computer and use it in GitHub Desktop.
Python Private Member Black Magic
class Vault(object):
#here's our private variable
__secret = "subtle and insubstantial, the expert leaves no trace"
#getter method to return the secret variable
def get_secret(self):
return self.__secret
fort_knox = Vault()
try:
#this will throw an error because __secret is private
print fort_knox.__secret
print "Accessed directly."
except:
#print using our getter
print fort_knox.get_secret()
print "Accessed via getter."
#but, accessing private members from a getter is no fun
#let's take a walk on the wild side
print fort_knox._Vault__secret
print "Accessed via shadow attribute"
#how is that possible, you ask?
#let's run dir() on our fort_knox object
print dir(fort_knox)
#you'll see that Python creates a shadow attribute for __secret
#so, nothing is really private
#can we change the value of __secret via its shadow attribute?
fort_knox._Vault__secret = "show him a road to safety, then strike."
try:
#this will throw an error because __secret is private
print fort_knox.__secret
print "Accessed directly."
except:
#print using our getter
print fort_knox.get_secret()
print "Accessed via getter."
#the answer is yes
#changing the shadow attribute changes the original attribute
#amazing. mind = blown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment