470,636 Members | 1,647 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,636 developers. It's quick & easy.

how do I make a class global?


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
e.new('ETestEvent', 'test')

Apr 27 '06 #1
1 2306
basically, you can create new types on the fly using type() with three

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

then, you can assign this vlass to the golbal namespace using

globals()["className"] = my_class

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

def create_class(name,params) :
def cls_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:
instance = test_class()
print instance.params


Apr 27 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

12 posts views Thread by Gaurav Veda | last post: by
1 post views Thread by Fernando Arámburu | last post: by
2 posts views Thread by Shapper | last post: by
10 posts views Thread by Julia | last post: by
14 posts views Thread by lovecreatesbea... | last post: by
15 posts views Thread by =?Utf-8?B?UGF0Qg==?= | last post: by
10 posts views Thread by ma | last post: by
3 posts views Thread by Jeff | last post: by
1 post views Thread by Korara | last post: by
1 post views Thread by Stoney L | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.