Last active
December 11, 2015 13:48
-
-
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
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 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