[BangPypers] MetaClass in python

Nitin Kumar nitin.nitp at gmail.com
Tue Jan 11 08:45:02 CET 2011


Hi all,

I am trying to create one meta Class which can create classes at runtime.
This I am able to achieve by the code snippet below


>>> class ChattyType(type):
def __new__(cls, name, bases, dct):
print "Allocating memory for class", name
for attributeName, attribute in dct.items():
 if type(attribute) == FunctionType:
 attribute = function(attribute)
 dct[attributeName] = attribute
return type.__new__(cls, name, bases, dct)
def __init__(cls, name, bases, dct):
print "Init'ing (configuring) class", name
super(ChattyType, cls).__init__(name, bases, dct)


>>> abc = ChattyType('X',(unittest2.TestCase,),{'fn':2})
Allocating memory for class X
Init'ing (configuring) class X

but I am looking for one function for this class created above, which will
do some activities (say print some data) at run time.
what all changes can be added to MetaClass to achieve this??

or is there any better way for the same.

The above things I am doing to replace one existing class and its function
attribute depending on some condition. So I want to create new class itself
using MetaClass (bcoz there can be various class which need to be created at
runtime)

-- 
Nitin K


More information about the BangPypers mailing list