another question on metaclasses

Lulu of the Lotus-Eaters mertz at gnosis.cx
Tue Dec 10 14:27:19 EST 2002


mis6 at pitt.edu (Michele Simionato) wrote previously:
|to understand metaclasses and this is my first program using them.
|Here is the motivation for the script. It is very common to have a class
|B with some __init__ method which is extended in a derived class C:

I think this example is cool enough that I saved it.  But I still have
to wonder about this, much as I do about most metaclass examples,
whether one really -needs- metaclasses to do this.  Of even if there is
anything clearer, easier to maintain, or any other advantage, about this
style.

Unfortunately, most of the posts discussing metaclasses still seem to be
at the level of "I'm trying to think of something to do with
metaclasses" (I've posted some like this too, I don't mean it as a
criticism).

The way I would generally approach this issue is with something like:

    >>> class Super:
    ...     def __init__(self):
    ...         print "...in Super"
    ...         self.init()
    ...
    >>> class Child(Super):
    ...     def init(self):
    ...         print "...in Child"
    ...
    >>> c = Child()
    ...in Super
    ...in Child

You could make this better, of course:  maybe check for the '.init()'
method before calling it; or raise NotImplementedError specifically;
pass along some arguments to '.init()'; look through
'self.__class__.__bases__' for methods to call; and other stuff.  Is
there anything that the metaclass approach gets you that a variant on
this one does not?

Yours, Lulu...


--
mertz@  | The specter of free information is haunting the `Net!  All the
gnosis  | powers of IP- and crypto-tyranny have entered into an unholy
.cx     | alliance...ideas have nothing to lose but their chains.  Unite
        | against "intellectual property" and anti-privacy regimes!
-------------------------------------------------------------------------





More information about the Python-list mailing list