Created
June 28, 2012 15:30
-
-
Save n1k0/3012006 to your computer and use it in GitHub Desktop.
Attribute fallback in Python - useful when you cannot extend an existing class, or want a proxy
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 Bar(object): | |
def plop(self): | |
print 'plop' | |
class Foo(object): | |
def __init__(self): | |
self.bar = Bar() | |
def do(self): | |
print 'done' | |
def __getattribute__(self, attr): | |
try: | |
return object.__getattribute__(self, attr) | |
except AttributeError as initial: | |
try: | |
return object.__getattribute__(self.bar, attr) | |
except AttributeError: | |
raise initial | |
>>> Foo().do() | |
done | |
>>> Foo().plop() | |
plop | |
>>> Foo().unexistent | |
AttributeError: 'Foo' object has no attribute 'unexistent' |
... and/or gettattr?
You can't use them because they use __getattribute__
themselves… you'd be ending with recursion errors :)
ah. never mind, then
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
maybe use hasattr(), instead of the try... except?
http://docs.python.org/library/functions.html#hasattr