metaclasses

Gerard Flanagan grflanagan at gmail.com
Tue Mar 4 01:51:47 EST 2008


On Mar 4, 6:31 am, castiro... at gmail.com wrote:
> On Mar 3, 10:01 pm, Benjamin <musiccomposit... at gmail.com> wrote:
>
>
>
> > On Mar 3, 7:12 pm, castiro... at gmail.com wrote:
>
> > > What are metaclasses?
>
> > Depends on whether you want to be confused or not. If you do, look at
> > this old but still head bursting essay:http://www.python.org/doc/essays/metaclasses/.
>
> > Basically, the metaclass of a (new-style) class is responsible for
> > creating the class. This means when Python sees
> > class Foo(object):
> >     __metaclass__ = FooMeta
> > class FooMeta(type):
> >     def __new__(cls, name, bases, dct):
> >        #do something cool to the class
> >        pass
> > It asks FooMeta to create the class Foo. Metaclasses always extend
> > type because type is the default metaclass.
>
> But you can stack class decorations, but not class metas.
>
> @somethingcool1
> @somethingcool2
> class Foo:
>    pass
>
> * class Foo:
>    __metaclass__= MetaCool1, MetaCool
>
> * denotes malformed

-----------------------
class Meta1(type):

    def foo1(cls):
        print 'hello'

class Meta2(type):

    def foo2(cls):
        print 'castiron'

class Meta(Meta1, Meta2):
    pass

class Base(object):
    __metaclass__ = Meta


Base.foo1()
Base.foo2()

-----------------------

Gerard



More information about the Python-list mailing list