Hooks, aspect-oriented programming, and design by contract

Aahz Maruch aahz at panix.com
Fri Jan 25 21:43:22 EST 2002


[mucho snippo, glad my brain hasn't exploded yet]

In article <68m48.25286$Rv3.912713 at news2.tin.it>,
Alex Martelli  <aleax at aleax.it> wrote:
>
>Classic example might be "A class that keeps track of all of
>its instances ever created (and incidentally keeps them all alive,
>but you could remedy that with weakref)".  For this, you need
>to tweak both class creation (adding an empty list) and class
>calling, i.e. instance creation (appending to the list), right?
>
>class nifty(type):
>    def __init__(self, *args):
>        type.__init__(self, *args)
>        self._instances = []
>    def __call__(self, *args, **kwds):
>        result = type.__call__(self, *args, **kwds)
>        self._instances.append(result)
>        return result
>
>__metaclass__ = nifty
>
>class X:
>    def __init__(self, name):
>        self.name = name
>    def __str__(self):
>        return 'X(%s)'%self.name
>
>for c in 'ciao': X(c)
>
>for x in X._instances: print x
>
>Each instance of X is apparently created and immediately
>thrown away, but actually kept in X._instances -- because
>X's metaclass is nifty, so calling X runs nifty.__call__, which
>does that.  Maybe this can be seen to have some potential
>use and thus help see why one might want sometimes to
>use different metaclasses than the two provided ones...?

Well, this is unfortunately a poor example for my little Pooh brain,
because I can do this just as easily with:

class X:
    _instances = []
    def __init__(self, name):
        self.name = name
        _instances.append(self)
    def __str__(self):
        return 'X(%s)' % self.name

I guess I can *almost* see your point in that if I want a whole slew of
classes to have that behavior, I can just set the metaclass, but given
how much repetition is already done in most __init__ clauses, I still
don't completely get it.
-- 
                      --- Aahz  <*>  (Copyright 2002 by aahz at pobox.com)

Hugs and backrubs -- I break Rule 6                 http://www.rahul.net/aahz/
Androgynous poly kinky vanilla queer het Pythonista   

"I support family values -- Addams family values" --www.nancybuttons.com



More information about the Python-list mailing list