Does Python have something like anonymous inner classes of Java?

后端 未结 10 1237
一生所求
一生所求 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条回答
  •  -上瘾入骨i
    2020-12-05 10:19

    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.

提交回复
热议问题