Does Python have something like anonymous inner classes of Java?

后端 未结 10 1242
一生所求
一生所求 2020-12-05 09:25

In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.

Suppose that you

10条回答
  •  执笔经年
    2020-12-05 10:07

    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)

提交回复
热议问题