properties and formatting with self.__dict__

Alex Martelli aleax at aleax.it
Sat Feb 22 17:57:36 EST 2003


Andrew Bennetts wrote:
   ...
> I find the similarities (and differences) between subclassing and
> instantiating interesting -- if you squint, they could almost be the same
> concept ;)

Yes, in prototype-based OO languages they essentially are.

> Things like Zope's acquisition and even Twisted's adapters (which were
> inspired by Zope 3, I think) are also similar; objects that delegate much
> of their behaviour to other objects.  Sometimes

Right.  Except that here we exploit the specific delegation
a Python instance does to the class it belongs to.

>> I like this because it seems to me to give a little
>> bit of the flavour and usefulness of prototype-based
>> languages, even though Python is class/instance-based.
> 
> What do you mean by prototype-based languages?

http://dmoz.org/Computers/Programming/Languages/Prototype-based/

>> Since an instance's __class__ attribute IS dynamically
>> assignable we could even have a dynamic variation of
>> this -- but I won't push the idea any further, as it
>> does seem to be out on a limb already.  NEAT though...
> 
> I'm curious to know what you were thinking of here.

Say that MOST instances of class X do not need per-instance
properties nor per-instance customization of e.g. __str__,
let's take the latter for simplicity.  We can still do it
only for those instances that actually NEED it:

class X(object):
    def __str__(self): return 'normal'

def makeSpecial(x):
    class subX(x.__class__):
        def __str__(self): return 'special'
    x.__class__ = subX

obviously this can be refined (e.g. trying to ensure that
more than one call to makeSpecial on the same instance
does not uselessly generate sub-sub-sub-classes -- for
example, here, checking if x.__class__.__str__ is or is
not X.__str__ might suffice), but I hope the fundamental
idea is pretty clear anyway.


>> And surely this CAN usefully be packaged into a custom
>> metaclass -- WITHOUT the kind of overhead I had in
>> mind at first (customizing __getattribute__, eek) but
>> just with a tiny little effort at instantiation time
>> (and THAT is generally quite affordable overhead).  But
>> that will wait, as it's not too hard anyway.
> 
> Hah!  That's a bold claim, considering what happened when I claimed
> something was "fairly easy".  :D

Writing a custom metaclass to ensure all classes that are
its instances have a __new__ that follows a certain pattern
is not hard -- not a particularly bold claim.  Particularly
in a case like this, where the "certain pattern" is such a
good match for the Template DP in the psychedelic Python
variant thereof (but, on Psychedelic Template, I hope to
get a chance to talk at next IPC;-).


Alex






More information about the Python-list mailing list