gpt4 book ai didi

python - Python 中的多态性

转载 作者:太空宇宙 更新时间:2023-11-03 13:05:31 26 4
gpt4 key购买 nike

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.__read() 而不是 File.__read() 来将我的代码修复为 FileA? :S

提前谢谢你。

最佳答案

用双下划线作为属性前缀不会使属性成为私有(private)属性,它只会使多态性变得不可能,因为属性名称会与当前 类名称混淆。改为将其更改为单个下划线前缀。

关于python - Python 中的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3964929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com