Python有什么东西像匿名内部类的Java? [英] Does Python have something like anonymous inner classes of Java?
问题描述
在Java中,您可以使用匿名内部类来内联定义一个新类。这在需要重写类的单个方法时非常有用。
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.
假设您想要创建 OptionParser
只覆盖一个方法(例如 exit()
)。在Java中你可以这样写:
Suppose that you want create a subclass of OptionParser
that overrides only a single method (for example exit()
). In Java you can write something like this:
new OptionParser () {
public void exit() {
// body of the method
}
};
这段代码创建一个匿名类,扩展 OptionParser
并覆盖 exit()
方法。
This piece of code creates a anonymous class that extends OptionParser
and override only the exit()
method.
Python中有类似的用法吗?
There is a similar idiom in Python? Which idiom is used in these circumstances?
推荐答案
您可以使用 type(name,bases,dict)
内建功能即时创建类。例如:
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()
由于OptionParser不是new-style类,你必须在基类列表中显式包含 object
。
Since OptionParser isn't a new-style class, you have to explicitly include object
in the list of base classes.
这篇关于Python有什么东西像匿名内部类的Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!