Skip to content

Instantly share code, notes, and snippets.

@tiagocoutinho
Created April 23, 2016 13:06
Show Gist options
  • Save tiagocoutinho/b3fd14fe5da3c88a0f386a9b5ac89b22 to your computer and use it in GitHub Desktop.
Save tiagocoutinho/b3fd14fe5da3c88a0f386a9b5ac89b22 to your computer and use it in GitHub Desktop.
Python object proxy
'''
An implementation object proxy pattern in python
Example::
from proxy import Proxy
class A(object):
def __init__(self, base):
self.base = base
def plus(self, *a):
return sum(a) + self.base
_a = A()
a = Proxy(a)
print(a.plus(3,4,5))
'''
class Proxy(object):
def __init__(self, wrapped):
self.__dict__['__wrapped__'] = wrapped
try:
self.__name__ = wrapped.__name__
except AttributeError:
pass
@property
def __class__(self):
return self.__wrapped__.__class__
def __getattr__(self, name):
return getattr(self.__wrapped__, name)
def __setattr__(self, name, value):
setattr(self.__wrapped__, name, value)
def main():
class A(object):
def plus(self, *a):
return sum(a)
_a = A()
a = Proxy(_a)
print(a.__class__.__name__)
print(a.plus(5, 6, 7))
a.hello = 'world'
print(_a.hello)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment