Python中与Java抽象类等价的是什么?

1 投票
1 回答
1291 浏览
提问于 2025-04-18 08:52

我有一些Java编程的经验,但现在我不得不使用Python来编程。我想做的是开发一个类结构,从一个抽象类Document开始,向下延伸到多个文档类型,这些文档类型会根据它们的类型从数据库中获取不同的信息。因为可能有至少一百种不同的文档类型,所以我觉得使用抽象来尽量减少上层结构的代码是我最好的选择。

在Java中,我会写类似这样的代码:

public abstract class Document(){
    private String department
    private String date
    ...
    public Document(){
    ...}
    public abstract String writeDescription(){
    ...}
}

在Python中,我不太确定最好的选择是什么。目前,我看到的两个主要选项是使用abc插件(https://docs.python.org/2/library/abc.html),或者直接使用基本的Python继承结构,像这样:Python中的抽象?

我能在不使用这个abc插件的情况下完成我的需求吗?还是说为了实现我的目标,使用它是必要的?

1 个回答

3

在Java中使用这种严格的结构的好处是,编译时会检查子类是否遵循它们的ABC所定义的规则。虽然在Python中你也可以使用继承和多态,但你不会自动得到任何静态检查。

我会在普通的Python中定义一个ABC,并为你希望所有文档都支持的功能写一些方法的空壳。

class Document(object):
    def __init__(self):
        pass  # do stuff

    def getDescription(self):
        raise NotImplementedError("getDescription() in Document is not implemented")

class DocumentImpl(Document)
    def __init__(self):
        super(DocumentImpl, self).__init__()

    def getDescription(self):
        return "this is a document impl"

撰写回答