Question about metaclass

Makoto Kuwata kwa at kuwata-lab.com
Wed Nov 2 00:02:40 EDT 2011


Hi,

I want to define a special class which groups functions, like:

    class Greepting(FuncGroup):
        def hello():          # no self, no @staticmethod!
            print("Hello!")
        def goodbye():        # no self, no @staticmethod!
            print("Good Bye!")

    Geeting.hello():    #=> "Hello!"
    Geeting.goodbye():  #=> "Good Bye!"


I tried the following code which converts instance mthods into
static method automatically, but I don't get result what I want.
(python 2.5.5)

    import sys
    from types import FunctionType

    class MetaClass(type):
        def __init__(cls, name, bases, dct):
            ## converts instance methods to static methods automatically
            for k in dct.keys():
                v = dct[k]
                if isinstance(v, FunctionType):
                    dct[k] = staticmethod(v)
                    print("*** debug: dct[%r] = %r" % (k, dct[k]))
#=> <staticmethod object at 0x100378d38>

    class FuncGroup(object):
        __metaclass__ = MetaClass

    class Greeting(FuncGroup):
        def hello():
            print("Hello!")
        def goodbye():
            print("Good Bye!")

    print("*** type(Greeting.hello)=%r" % type(Greeting.hello)
#=> <type 'instancemthod'>
    print("*** type(Greeting.goodbye)=%r" % type(Greeting.goodbye)
#=> <type 'instancemthod'>


Could you give me advice?

--
regards,
makoto kuwata



More information about the Python-list mailing list