Does Python have something like anonymous inner classes of Java?

后端 未结 10 1276
一生所求
一生所求 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: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()
    

提交回复
热议问题