How to instantiate in a lazy way?

Nick Craig-Wood nick at craig-wood.com
Wed Dec 3 15:30:48 CET 2008


Slaunger <Slaunger at gmail.com> wrote:
>  On 3 Dec., 11:30, Nick Craig-Wood <n... at craig-wood.com> wrote:
> > > ? ? ? ? ?cls = self.__class__
> > > ? ? ? ? ?if attr_name in cls.data_attr_names:
> >
> > self.data_attr_names should do instead of cls.data_attr_names unless
> > you are overriding it in the instance (which you don't appear to be).
> 
>  Yeah, I know. I just like the cls notation for code readability
>  because it tells you that it is a class attribute, which is not
>  instance- dependent.
> 
>  That may be legacy from my Java past, where I used to do it that
>  way.  I know perfectly well that self. would do it. i just find
>  that notation a little misleading

I quite like it... It looks in the instance, then in the class which I
find to be very elegant - you can set a default in the class and
override it on a per object or per subclass basis.

> > I think you want setattr() here - __dict__ is an implemetation detail
> > - classes with __slots__ for instance don't have a __dict__. ?I'd
> > probably do this
> 
>  Oh my, I did not know that. __slots__?? Something new I got to
>  understand.  But you are right. thanks!
> 
> >
> > ? ? ? ? ? ? ? ? ? ?for k, v in zip(("I1", "Q1", "I2", "Q2"), bytes_to_data(buf)):
> > ? ? ? ? ? ? ? ? ? ? ? ?setattr(self, k, v)
> > ? ? ? ? ? ? ? ? ? ?return object.__getattr__(self, attr_name)
> >
>  And perhaps even more readable (how I do it now, no need to call
>  __getattr__ for an attribute, whcih is already there):
>                  ...
>                  for attr, value in zip(cls.data_attr_names,
>  bytes_to_data(buf)):
>                      setattr(self, attr, value)
> 
>                  return getattr(self, attr_name)

I wrote the object.__getattr__ call to stop recursion troubles.  If
you are sure you've set the attribute then plain getattr() is OK I
guess...

>  In this process I have actaully managed to isolate all the
>  ...OnDemand stuff in an abstract PayloadOnDemand class
> 
>  I can now use this "decorator-like"/helper class to very easily
>  make an ...OnDemand variant of a class by just doing multiple
>  inheritance - no implementation:
> 
>  class PayloadBaconAndEggsOnDemand(PayloadOnDemand, PayloadBaconAndEggs): pass

You've reinvented a Mixin class!

  http://en.wikipedia.org/wiki/Mixin

It is a good technique.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list