Python Meta Classes ROCK!!

I’ve been trying to do this for a long time, but could never find a way.  Today I actually spent some time reading up on how metclasses work, and bam!

The goal is to have a base class, which has a method called “init_done()”.  I want this method to be called after the actual object is initialized.  That doesnt sound to bad, but try doing it and still have it be called after all calls to __init__ are done once you start subclassing (you only want it called once at the end, not after every parent calss’ call to __init__)!

So here it goes (I’m also adding a nifty print statement that one can exchang for e.g.  autoregister all your subclasses in a factory or something like that ).

class MyType(type):
    def __new__(cls, name, bases, attrs):
        init = attrs['__init__']
        def call_me_after_init(self,*args,**kwargs):
            if type(self) == eval(name):
                print "AFTER init!!",   #or attrs['init']
        attrs['__init__'] = call_me_after_init
        return super(MyType, cls).__new__(cls, name, bases, attrs)

    def __init__(self, name, bases, attrs):
        super(MyType, self).__init__(name, bases, attrs)
        print "Register me in factory!  name:", name, "self:", self

class A(object):
    __metaclass__ = MyType
    def __init__(self, a):
        print "init A", a

class B(A):
    def __init__(self, a):
        print "init B start", a
        super(B, self).__init__(a)
        print "init B end", a

test = B("test")

This is the output:

Register me in factory! name: A self:
Register me in factory! name: B self:
init B start test
init A test
init B end test
AFTER init?!


This entry was posted in programing, python. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WP Hashcash