How to wrap a class's methods?
Grant Edwards
grante at visi.com
Thu Feb 17 16:10:02 EST 2005
On 2005-02-17, Mathias Waack <M.Waack at gmx.de> wrote:
> How about using a delegator:
>
> class Wrapper:
> funcs = ("login", "list", "search")
> def __init__(self, classobj):
> self.__wrapped = classobj()
> def __getattr__(self, attr):
> if attr in Wrapper.funcs:
> def f(*args):
> f1 = getattr(self.__wrapped, attr)
> s,r = f1(args)
> if s != 'OK': raise NotOk((s,r))
> return r
> return f
> # raise some exception here
> imap = Wrapper(imaplib.IMAP4_SSL)
>
> If you wrap all methods you can ignore the if-test.
I'm not, and the other methods should behave "normally":
class Wrapper:
funcs = ("login", "list", "search")
def __init__(self, classobj):
self.__wrapped = classobj()
def __getattr__(self, attr):
if attr in Wrapper.funcs:
def f(*args):
f1 = getattr(self.__wrapped, attr)
s,r = f1(args)
if s != 'OK': raise NotOk((s,r))
return r
else:
f = getattr(self.__wrapped, attr)
return f
> PS: note that we're wrapping the instance's methods, not the class's
> methods!
You're right.
--
Grant Edwards grante Yow! "THE LITTLE PINK
at FLESH SISTERS," I saw them
visi.com at th' FLUROESCENT BULB
MAKERS CONVENTION...
More information about the Python-list
mailing list