question on creating class

Jussi Salmela tiedon_jano at hotmail.com
Thu Jan 4 04:14:40 EST 2007


wcc kirjoitti:
> Hello,
> 
> How do I create a class using a variable as the class name?
> 
> For example, in the code below, I'd like replace the line
> 
> class TestClass(object):
> with something like
> class eval(className) (object):
> 
> Is it possible?  Thanks for your help.
> 
> className = "TestClass"
> 
> class TestClass(object):
>     def __init__(self):
>         print "Creating object of TestClass..."
> 
>     def method1(self):
>         print "This is a method."
> 
> if __name__ == "__main__":
>     o = TestClass()
>     o.method1()
> 
> --
> wcc
> 

I'm curious: what is the original problem that you are trying to solve?

The following works, but note that I'm no Python expert and if any of 
the regular wizards around here says that doing these kind of things is 
sick, I'm gonna agree 100%  ;)

className = "TestClass2"

class TestClass(object):
     def __init__(self):
         print "Creating object of TestClass..."

     def method1(self):
         print "This is a method."

exec('class ' + className +
     '''(object):
     def __init__(self):
         print "Creating object of TestClass2..."

     def method1(self):
         print "This is a method1 of TestClass2."
''')

if __name__ == "__main__":
     o = TestClass()
     o.method1()
     o2 = TestClass2()
     o2.method1()
     o2 = locals()[className]()
     o2.method1()



More information about the Python-list mailing list