标准库 open
函数作为一个函数工作:
f = open('file.txt')
print(type(f))
<type 'file'>
或作为上下文管理器:
with open('file.txt') as f:
print(type(f))
<type 'file'>
我正在尝试使用
contextlib.closing
模仿这种行为,其中 File
是我的自定义文件 I/O 类:def myopen(filename):
f = File(filename)
f.open()
return closing(f)
这作为上下文管理器按预期工作:
with myopen('file.txt') as f:
print(type(f))
<class '__main__.File'>
但当然,如果我直接调用,我会返回
closing
对象而不是我的对象:f = myopen(filename)
print(type(f))
<class 'contextlib.closing'>
那么,我如何实现
myopen
以便它既可以用作上下文管理器,又可以在直接调用时返回我的 File 对象?github上的完整工作示例:
https://gist.github.com/1352573
最佳答案
最简单的事情可能是自己实现__enter__
和__exit__
方法。像这样的事情应该这样做:
class File(object):
# ... all the methods you already have ...
# context management
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
顺便说一句,在
open
方法中完成 __init__
方法的工作会更惯用。关于python - 如何使用 Python 关闭上下文管理器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8070259/