Python 中的多态性
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
提前谢谢你。
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
My question: what's wrong? How I can fix my code to FileA use FileA.__read()
to read the file instead of File.__read()
? :S
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用双下划线作为属性前缀并不会使该属性成为私有属性,它只是使多态性变得不可能,因为属性名称与当前类名称混淆了。将其更改为单个下划线前缀。
Prefixing an attribute with double underscores doesn't make the attribute private, it simply makes polymorphism impossible because the attribute name gets mangled with the current class name. Change it to a single underscore prefix instead.
您还可以在基类中保留未定义的方法以达到相同的效果。
对类继承的理解对于理解 Python 类是非常宝贵的。
You can also leave the method undefined in the base class to achieve the same effect.
It is invaluable to the understanding of Python classes to have this understanding of class inheritance.