Does Python have something like anonymous inner classes of Java?

Java uses anonymous classes mostly to imitate closures or simply code blocks. Since in Python you can easily pass around methods there's no need for a construct as clunky as anonymous inner classes:

def printStuff():
   print "hello"

def doit(what):
   what()

doit(printStuff) 

Edit: I'm aware that this is not what is needed in this special case. I just described the most common python solution to the problem most commonly by anonymous inner classes in Java.


You can accomplish this in three ways:

  1. Proper subclass (of course)
  2. a custom method that you invoke with the object as an argument
  3. (what you probably want) -- adding a new method to an object (or replacing an existing one).

Example of option 3 (edited to remove use of "new" module -- It's deprecated, I did not know ):

import types
class someclass(object):
    val = "Value"
    def some_method(self):
        print self.val

def some_method_upper(self):
    print self.val.upper()

obj = someclass()
obj.some_method()

obj.some_method = types.MethodType(some_method_upper, obj)
obj.some_method()

You can use the type(name, bases, dict) builtin function to create classes on the fly. For example:

op = type("MyOptionParser", (OptionParser,object), {"foo": lambda self: "foo" })
op().foo()

Since OptionParser isn't a new-style class, you have to explicitly include object in the list of base classes.


Well, classes are first class objects, so you can create them in methods if you want. e.g.

from optparse import OptionParser
def make_custom_op(i):
  class MyOP(OptionParser):
    def exit(self):
      print 'custom exit called', i
  return MyOP

custom_op_class = make_custom_op(3)
custom_op = custom_op_class()

custom_op.exit()          # prints 'custom exit called 3'
dir(custom_op)            # shows all the regular attributes of an OptionParser

But, really, why not just define the class at the normal level? If you need to customise it, put the customisation in as arguments to __init__.

(edit: fixed typing errors in code)