question on creating class

Thomas Heller theller at ctypes.org
Thu Jan 4 04:08:42 EST 2007


wcc schrieb:
> 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
> 

You call 'type' to create a new-style class.  The signature is:
"type(name, bases, dict) -> a new type".

>>> def __init__(self):
...     print "Creating object of TestClass..."
...
>>> def method1(self):
...     print "This is a method"
...
>>> TestClass = type("TestClass", (), {"__init__": __init__, "method1": method1})
>>>
>>>
>>> help(TestClass)
Help on class TestClass in module __main__:

class TestClass(__builtin__.object)
 |  Methods defined here:
 |
 |  __init__(self)
 |
 |  method1(self)
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __dict__ = <dictproxy object>
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__ = <attribute '__weakref__' of 'TestClass' objects>
 |      list of weak references to the object (if defined)

>>> TestClass()
Creating object of TestClass...
<__main__.TestClass object at 0x00AED0B0>
>>> TestClass().method1()
Creating object of TestClass...
This is a method
>>>


Thomas




More information about the Python-list mailing list