Skip to content

Instantly share code, notes, and snippets.

@fjorgemota
Last active December 11, 2015 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjorgemota/4609844 to your computer and use it in GitHub Desktop.
Save fjorgemota/4609844 to your computer and use it in GitHub Desktop.
Simple example of a pratical method to create private attributes in Python using functions closures
class People:
'''Just a class to save the name of a people'''
def __init__(self, name):
'''Just saves the name of a people'''
obj = {} #A internal variable to save the state of the attribute
def setName(new_name):
'''Just a function to set the name of a people'''
obj["name"] = new_name #It's available in the internal variable representation
self.setName = setName #Just point it to the object
def getName():
'''Just return the name of a people, configurated in the object'''
return obj["name"]
self.getName = getName
obj["name"] = name
#Just it, now, to test...
fernando = People("Fernando")
print fernando.getName() #Returns the name "Fernando"
print fernando.name #Returns attribute error
print fernando.obj #Returns attribute error too
fernando.setName("Just a test")
print fernando.getName() #Returns 'Just a test'..Only this =P
# Cool, not?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment