how do I make a class global?

T

Tom Brown

Hi,

I thought it would be nifty to create a class that created other classes for
me. The method below shows what I would like to do. The problem is that the
class the method creates is local to the method. Is it possible to make the
class visible in the global scope so I can import the module see the
dynamically created classes? Or do I need to generate a source file and do a
'from tmp import *'?

def new(self, eventType, param):
self.value += 1
exec 'global %s; %s = %d' % (eventType, eventType, self.value)
sl = []
sl.append('class %sEvent(QEvent):' % eventType)
sl.append(' def __init__(self, %s):' % param)
sl.append(' QEvent.__init__(self, %s)' % evenType)
sl.append(' self.%s = %s' % (param, param))
source = '\n'.join(sl)
co = compile(source, 'tmp.py', 'exec')
exec co

Then, to create another event, I would just have to add another line like
this:
e.new('ETestEvent', 'test')

Thanks,
Tom
 
H

harold

basically, you can create new types on the fly using type() with three
arguments:

my_class = type("className",(BaseClass,),class_dict)

then, you can assign this vlass to the golbal namespace using
globals():

globals()["className"] = my_class

In your case, you would need to populate the class_dict by a function
object
that you parameterize to your needs, e.g.

def create_class(name,params) :
def cls_init(self) :
BaseClass.__init__(self)
self.params = params

cls_dict = {
"__init__" : cls_init
}

new_cls = type(name,(BaseClass,),cls_dict)
globals()[name] = new_cls

the result would be like this:
42
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top