Subclass factories?
Jeff Epler
jepler at inetnebr.com
Sun Mar 11 21:12:54 EST 2001
On Mon, 12 Mar 2001 11:23:24 +1100, Tim CHURCHES
<TCHUR at doh.health.nsw.gov.au> wrote:
>If the subclass factory approach is reasonable, what is the best way
>to do it? So far I been assembling the necessary statements for the
>new class definition into a string then exec'ing that string, but that
>seems rather inelegant. I'm sure there must be a better way.
Use the "new" module to create a class with a particular list of superclasses
and a particular dictionary of functions or attributes.
Example:
>>>import new
>>> class A:
... pass
>>> class B:
... pass
>>>def f(self):
... print "it's f", self
>>> D = new.classobj("from new.classobj", (A, B), {"f": f})
>>> print D.__bases__
(<class __main__.A at 80c5080>, <class __main__.B at 80c6a10>)
>>> print dir(D)
['__doc__', '__module__', 'f']
>>> d = D()
>>> print d.f()
it's f <__main__.from new.classobj instance at 80c5b00>
Jeff
More information about the Python-list
mailing list