Revision 1 as of 2003-11-17 22:47:54

Clear message

Proxy

See also http://www.python.org/workshops/1997-10/proceedings/savikko.html

special method names


pro


cons

Toggle line numbers
   1 # Code is Public Domain.
   2 class Proxy(object):
   3     def __init__(self, subject):
   4         self._subject = subject
   5         
   6     def __getattr__(self, attrName):
   7         return getattr(self._subject, attrName)
   8     
   9     def __setattr__(self, attrName, value):
  10         object.__setattr__(self, attrName, value)
  11 
  12     def __delattr__(self, attrName):
  13         delattr(self._subject, attrName)
  14 
  15     def __call__(self,*args,**keys):
  16         apply(object.__getattribute__(self,'_subject'),args,keys)
  17 
  18     def __getitem__(self,key):
  19         return object.__getattribute__(self,'_subject')[key]
  20 
  21 ##    should implement other special method names here
  22 
  23 class Test:
  24     def __init__(self):
  25         self.toto = "toto"
  26 
  27     def foo(self):
  28         print "foo"
  29 
  30     def __call__(self,a,b,more=False):
  31         print self.__class__.__name__,id(self)
  32         print a,b,more
  33 
  34     def __getitem__(self,key):
  35         return 'Test%s' % key
  36 
  37 t = Test()
  38 p = Proxy(t)
  39 
  40 print p.toto
  41 p.foo()
  42 p('1',2,more=True)
  43 print p['Blabla']

Unable to edit the page? See the FrontPage for instructions.