instance/class methods: having my cake and eating it too

Thomas Heller theller at python.net
Fri Aug 30 17:38:54 CEST 2002


"Donnal Walter" <donnal at donnal.net> wrote in message news:918bc22f.0208300723.5d7df621 at posting.google.com...
> "Thomas Heller" <theller at python.net> wrote:
> > Classes deriving from object can completely customize
> > the binding process by implementing a __get__ method:
> >
> > class _BoundMethod:
> >     # Helper class.
> >     def __init__(self, func, first):
> >         self.func = func
> >         self.first = first
> >
> >     def __call__(self, *args):
> >         return self.func(self.first, *args)
> >
> > class unimethod(object):
> >     # universal method: binds to either a class or an instance
> >     def __init__(self, func):
> >         self.func = func
> >
> >     def __get__(self, inst, type=None):
> >         if inst is None:
> >             # bind to the class
> >             return _BoundMethod(self.func, type)
> >         else:
> >             # bind to the instance
> >             return _BoundMethod(self.func, inst)
> >
> > Then you can do:
> >
> > class Decimal:
> >     ...
> >     def SetDigits(cls_or_inst, ...):
> >         ....
> >
> >     SetDigits = unimethod(SetDigits)
> >
> > -----
> >
> > Thomas
>
> Thank you for this answer. It is *exactly* what I was looking for. I
> had previously studied PEP 252 and other documentation related to it,
> but somehow I don't think I ever would have come up with this solution
> on my own. Now that I have seen your working example, however, I
> understand better how descriptors work, and I thank you very much.
>
> Donnal
The most useful reading about this stuff I found is Guido's introduction
http://www.python.org/2.2.1/descrintro.html.

Although, unfortunately, still some important stuff is missing,
see the 'Additional Topics' section at the end.

Thomas





More information about the Python-list mailing list