Does Python have something like anonymous inner classes of Java?

后端 未结 10 1141
一生所求
一生所求 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 09:53

    You can always hide class by variables:

     class var(...):
         pass
     var = var()
    

    instead of

     var = new ...() {};
    
    0 讨论(0)
  • 2020-12-05 09:55

    In python you have anonymous functions, declared using lambda statement. I do not like them very much - they are not so readable, and have limited functionality.

    However, what you are talking about may be implemented in python with a completely different approach:

    class a(object):
      def meth_a(self):
        print "a"
    
    def meth_b(obj):
      print "b"
    
    b = a()
    b.__class__.meth_a = meth_b
    
    0 讨论(0)
  • 2020-12-05 09:58

    Python doesn't support this directly (anonymous classes) but because of its terse syntax it isn't really necessary:

    class MyOptionParser(OptionParser):
        def exit(self, status=0, msg=None):
            # body of method
    
    p = MyOptionParser()
    

    The only downside is you add MyOptionParser to your namespace, but as John Fouhy pointed out, you can hide that inside a function if you are going to do it multiple times.

    0 讨论(0)
  • 2020-12-05 09:58

    This is what you would do in Python 3.7

    #!/usr/bin/env python3
    class ExmapleClass:
        def exit(self):
            print('this should NOT print since we are going to override')
    
    ExmapleClass= type('', (ExmapleClass,), {'exit': lambda self: print('you should see this printed only')})()
    ExmapleClass.exit()
    
    0 讨论(0)
  • 2020-12-05 10:07

    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()
    
    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题