我有一些使用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继承结构,如下所示:Abstraction in Python?
如果没有这个abc插件,我可以完成我需要的东西,还是有必要做我想做的事情?
答案 0 :(得分:0)
在Java中使用这种严格结构的优点是你有编译时检查子类是否满足ABC定义的契约。您仍然可以在python中使用继承和多态,但是您不会免费获得任何静态检查。
我要做的是在vanilla 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"