我正在尝试创建一个可以很好地与 Python 中的 with
关键字配合使用的对象。我知道您必须创建 __enter__
和 __exit__
方法,但我不太确定如何操作该对象。作为一个具体示例,我编写了一个创建本地工作空间并在退出时清理的类:
import tempfile, os, shutil
class temp_workspace(object):
def __enter__(self):
self.local_dir = os.getcwd()
self.temp_dir = tempfile.mkdtemp()
os.chdir(self.temp_dir)
def __exit__(self, exc_type, exc_value, traceback):
os.chdir(self.local_dir)
shutil.rmtree(self.temp_dir)
def __repr__(self):
return self.temp_dir
这工作得很好,但是当我尝试打印本地目录名称时:
with temp_workspace() as T:
print "Temp directory name is ", T
它显示为 None
并且 __repr__
甚至没有被调用!这真的很令人困惑,因为 T
也是 NoneType
。我做错了什么?
最佳答案
您没有按照 context manager protocol 的指定从 __enter__
返回对象.将 return self
添加到 __enter__
方法的末尾。
关于python - 对于在 python 中使用 `with` 关键字的类,我可以让它 __repr__ (打印)本身吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14432790/