metaclasses and static methods

Lulu of the Lotus-Eaters mertz at gnosis.cx
Sat Dec 14 15:02:02 EST 2002


mis6 at pitt.edu (Michele Simionato) wrote previously:
|The solution is an eight lines helper class RecognizeStatic:
|  class RecognizeStatic(object):
|      class __metaclass__(type):
|          def __init__(cls,name,bases,clsdict):
|              from inspect import isfunction
|              for key,value in clsdict.items():
|                  if isfunction(value) and key.startswith("static_"):
|                      value=staticmethod(value)
|                      setattr(cls,key[7:],value)


Ahh... not to be such a thorn in your paw, Michele, but what about the
following (6-line :-)) class:

class RecognizeStatic_Traditional:
    def __init__(self):
        from inspect import isfunction
        for k,v in self.__class__.__dict__.items():
            if k.startswith('static_') and isfunction(v):
                self.__class__.__dict__[k[7:]] = staticmethod(v)


Now of course, if your 'C(RecognizeStatic_Traditional)' class decides to
have an '.__init__()' method, you'll need to call the parent's init.
You could also call the parent method something like
'.methods2static()', and call it explicitly when you wanted that to
happen.

But this is my ongoing challenge to have someone show me what
metaclasses are *really* doing, other than changing spelling a bit.
Mind you, I'm sure I'll see it in time (since the Martellibot thinks
there is something to see).

Yours, Lulu...

--
 mertz@   _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i
gnosis  _/_/                    Postmodern Enterprises         _/_/  s r
.cx    _/_/  MAKERS OF CHAOS....                              _/_/   i u
      _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/    g s





More information about the Python-list mailing list