Last active
August 29, 2015 13:55
-
-
Save JensTimmerman/8690130 to your computer and use it in GitHub Desktop.
python encapsulation example
This file contains hidden or 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 Student(object): | |
def __init__(self, name): | |
# define your internal stuff here, with self.__dict__ | |
self.__dict__['name'] = name | |
def __getattr__(self, attr): | |
return self.name.__getattribute__(attr) | |
def from_str(self, txt): | |
self.name = txt | |
def __setattr__(self, attr, value): | |
if not attr in self.__dict__: | |
return self.name.__setattr__(attr, value) | |
else: | |
self.__dict__[attr] = value | |
student = Student('test') | |
print student.upper() | |
>>>TEST | |
student.from_str('foo') | |
>>> print student.upper() | |
FOO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment