Created
August 28, 2014 17:54
-
-
Save bbengfort/c27a9f8492a0e0f18ee3 to your computer and use it in GitHub Desktop.
Internal Accessor
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 Person(object): | |
def __init__(self, name, age, profile): | |
self.name = name | |
self.age = age | |
self.profile = profile | |
def __getattr__(self, key): | |
if hasattr(self, key): | |
return getattr(self, key) | |
elif hasattr(self.profile, key): | |
return getattr(self.profile, key) | |
else: | |
raise AttributeError("No value '%s' on Person" % key) | |
if __name__ == "__main__": | |
profile = { | |
'handle': '@bbengfort', | |
'tweets': 52, | |
} | |
person = Person('Benjamin Bengfort', 42, profile) | |
print person.name # 'Benjamin Bengfort' | |
print person.age # 42 | |
print person.handle # '@bbengfort' | |
print person.tweets # 52 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment