Created
November 19, 2010 06:35
-
-
Save jbail/706193 to your computer and use it in GitHub Desktop.
Python Private Member Black Magic
This file contains 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 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