在下面的代码中,我不明白为什么with super().__init__(*args, **kwargs):MyFileIO2 中的行会抛出一个关于丢失的错误,__exit__而 MyFileIO 类一切正常。我真的不明白在 init 内部或外部执行 with 之间究竟有什么区别。有人可以启发我这里发生了什么吗?
import io
class MyFileIO(io.FileIO):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __enter__(self, *args, **kwargs):
f = super().__enter__(*args, **kwargs)
print('first byte of file: ', f.read(1))
return f
class MyFileIO2(io.FileIO):
def __enter__(self, *args, **kwargs):
f = super().__enter__(*args, **kwargs)
print('first byte of file: ', f.read(1))
return f
def __init__(self, *args, **kwargs):
with super().__init__(*args, **kwargs): # AttributeError: __exit__
pass
path = 'some_file.bin'
with MyFileIO(path, 'rb'):
pass
MyFileIO2(path, 'rb')
MMTTMM
相关分类