Late initialization using __getattribute__

bukzor workitharder at gmail.com
Thu Sep 4 15:38:45 EDT 2008


> > I'd like to be able to do something like this:
> > class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ...,
> > VanillaCursor): pass
>
> Why does it have to look like that?  A good programmer lets the code
> look however it has to look to most effectively do it's job.
>
> With a proxy, the "base class" isn't a base class but a member.  Here
> is a very simple example:
>
> class SuperCursor(object):
>     def __init__(self):
>         self._cursor = VanillaCursor()
>         self._connected = False
>     def __getattr__(self,attr):
>         if not self._connected:
>             self._cursor.connect()
>             self._connected = True
>         return getattr(self._cursor,attr)
>
> cursor = SuperCursor()
>
> That doesn't use a mixin, but why should it?

The point of using a mixin is to not limit myself to inheriting from
VanillaCursor. I want to put this on top of various subclasses of the
vanilla cursor, like TimeLimitedCursor or RetryingCursor. I have four
other mixins that operate this way, so it's desirable to keep this one
in line with that.



More information about the Python-list mailing list