All pastes #941757 Raw Edit

Stuff

public html v1 · immutable
·published 2008-03-13 22:31 UTC
rendered paste body
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:<pre name="code" class="python">import sysout = sys.stdout.write# If you like one-linersa = 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 variantdef __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))</pre>There are, ofcourse, some other ways to do it, and one could wrap around type for more functionality, but like this it works.