[Tutor] Metaclass confusion...

Modulok modulok at gmail.com
Tue Apr 19 15:38:26 CEST 2011


List,

I've been messing with metaclasses. I thought I understood them until I ran
into this. (See code below.) I was expecting the generated class, 'Foo' to have
an 'x' class-level attribute, as forced upon it by the metaclass 'DracoMeta'
at creation. Unfortunately, it doesn't and I don't know why. I'm obviously
missing something big. I thought a metaclass created the class object,
so this should work. (But obviously doesn't.)


<!-- Begin Code -->
class DracoMeta(type):
    '''Metaclass that creates a serial number as a class property.'''
    def __init__(self, name, bases, members):
        # Force a class attribute on the class-to-be:
        members['serial'] = 3

        # Now make the class:
        type.__init__(self, name, bases, members)

class Foo(object):
    __metaclass__ = DracoMeta

print hasattr(Foo, 'serial')    #<-- I was really expecting this to be True.
<!-- End Code -->

I could add the attribute in the definition or a decorator, but the point was
learning to use (albeit abuse) metaclasses. Anyway, if anyone could take
a look I'd be grateful.

Thanks!
-Modulok-


More information about the Tutor mailing list