【发布时间】:2010-10-19 02:32:20
【问题描述】:
class File(object):
def __init__(self, filename):
if os.path.isfile(filename):
self.filename = filename
self.file = open(filename, 'rb')
self.__read()
else:
raise Exception('...')
def __read(self):
raise NotImplementedError('Abstract method')
class FileA(File):
def __read(self):
pass
file = FileA('myfile.a')
# NotImplementedError: Abstract method
我的问题:怎么了?如何将我的代码修复为 FileA 使用 FileA.__read() 而不是 File.__read() 来读取文件? :S
提前谢谢你。
【问题讨论】:
-
值得注意的是,通过让基方法 raise
NotImplementedError来实现“抽象方法”会破坏多重继承。使用abc 模块是一种更好的方法。 -
@Michael Anderson:StackOverflow 维护着完整的更改日志。您无需发表评论表明您进行了更改。这很明显超越了重复。请删除您的评论。
标签: python methods polymorphism