Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 #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
You can’t perform that action at this time.