I have recently discovered that Python has a few ways of creating anonymous classes too :) But... as Tim Peters once said: "There should be one-- and preferably only one --obvious way to do it", the obvious way to do it is like this:
import sys
out = sys.stdout.write
# If you like one-liners
a = type('MyClass', dict=dict(__init__=lambda self: out("a's constructor\n"), foo=lambda self: out("a's foo\n")))
# Or the non-one-liner variant
def __init__(self):
print "%s's constructor" % (self.__class__.__name__)
'''Yes I know, a simple "a's constructor" would have worked too'''
def foo(self):
print "%s's %s" % (self.__class__.__name__, self.foo.__name__)
'''One again, "a's foo" would have been sufficient, but why repeat yourself?'''
a = type('a', dict=dict(__init__=__init__, foo=foo))
x = a()
x.foo()
print isinstance(x, a)
'''Want inheritance? The following class will inherit from both object and a'''
a = type('a', (object, a), dict(__init__=__init__, foo=foo))
There are, ofcourse, some other ways to do it, and one could wrap around type for more functionality, but like this it works.