Question about metaclass

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


On Wed, Nov 2, 2011 at 1:40 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>
> If you want to customize the dict you need to do it in __new__, not
> __init__.  By the time __init__ is called, the class has already been
> created.
>
> class MetaClass(type):
>    def __new__(mcs, name, bases, dict):
>        for k, v in dict.items():
>            if isinstance(v, FunctionType):
>                dict[k] = staticmethod(v)
>        return type.__new__(mcs, name, bases, dict)

Great! It works perfectly!


> If you were using a more recent Python version, I would suggest using
> a class decorator instead of a metaclass.  You can still do this in
> Python 2.5, but the syntax will be more awkward.
>
> # Python 2.6+
> def FuncGroup(class_):
>    for k, v in class_.__dict__.items():
>        if isinstance(v, FunctionType):
>            setattr(class_, k, staticmethod(v))
>    return class_
>
> @FuncGroup
> class Greeting(object):
>    def hello():
>        print("Hello!")
>
> # Python 2.5
> class Greeting(object):
>    def hello():
>        print("Hello!")
> Greeting = FuncGroup(Greeting)

This is so good method.
Thank you, Ian.

--
regards,
makoto kuwata



More information about the Python-list mailing list