Question about metaclass

Patrick Maupin pmaupin at gmail.com
Wed Nov 2 00:42:04 EDT 2011


On Nov 1, 11:02 pm, Makoto Kuwata <k... at kuwata-lab.com> wrote:
> 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

I think you need to unwrap the instance methods first:

>>> class foo(object):
...     def bar():
...         print "Hi there"
...
>>> foo.bar2 = staticmethod(foo.bar.im_func)
>>>
>>> foo.bar2()
Hi there
>>>




More information about the Python-list mailing list