classobj?

V

Venky

Hi,

I am trying to create classes at runtime based on input from a textfile.
I am trying to use the function new.classobj. I am able to create the
new classes successfully, however I fail to understand on how to add
this new class to the current dictionary.

cl = new.classobj('SomeClass', (BaseClass, ), {})

After this call, how do I instantiate SomeClass?

I understand cl() will instantiate this, however this defeats my
purpose, since the name of the class is obtained at runtime.

Thanks

venky
 
A

attn.steven.kuo

Hi,

I am trying to create classes at runtime based on input from a textfile.
I am trying to use the function new.classobj. I am able to create the
new classes successfully, however I fail to understand on how to add
this new class to the current dictionary.

cl = new.classobj('SomeClass', (BaseClass, ), {})

After this call, how do I instantiate SomeClass?

I understand cl() will instantiate this, however this defeats my
purpose, since the name of the class is obtained at runtime.


Do you mean that you want to add it to globals()?

globals()['SomeClass'] = cl

myinst = SomeClass()
print isinstance(myinst, SomeClass)
print isinstance(myinst, BaseClass)
 
V

Venky

....
Do you mean that you want to add it to globals()?

globals()['SomeClass'] = cl

myinst = SomeClass()
print isinstance(myinst, SomeClass)
print isinstance(myinst, BaseClass)

Thanks. That's what I was looking for.
 
M

Marc 'BlackJack' Rintsch

Do you mean that you want to add it to globals()?

globals()['SomeClass'] = cl

myinst = SomeClass()
print isinstance(myinst, SomeClass)
print isinstance(myinst, BaseClass)

Thanks. That's what I was looking for.

Probably not because now you have to know the name when you write the
static source code. You said the names are discovered at runtime, so how
do you know it's `SomeClass`? Put you classes into a dictionary with the
name as key.

`globals()` is a dictionary too, but it is more work to get an object by
name from it (globals()['SomeClass'] vs. some_dict['SomeClass']) and you
don't risk that some of your dynamically created classes overwrites an
existing one with the same name.

Ciao,
Marc 'BlackJack' Rintsch
 

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
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top