metaclasses

B

Benjamin

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.
 
C

castironpi

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
 
G

Gerard Flanagan

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()
 
C

castironpi

-----------------------
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()

class Base(object):
__metaclass__= type( 'Meta', ( Meta1, Meta2 ), {} )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top