对于在python中使用`with`关键字的类,我可以自己使用__repr __(print)吗?

Hoo*_*ked 3 python with-statement

我正在尝试创建一个与withPython中的关键字很好地匹配的对象.我知道你必须创建__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
Run Code Online (Sandbox Code Playgroud)

这工作正常,但当我尝试打印本地目录名称时:

with temp_workspace() as T:
    print "Temp directory name is ", T
Run Code Online (Sandbox Code Playgroud)

它显示为None__repr__不甚至被称为!这T也很令人困惑NoneType.我究竟做错了什么?

Bre*_*arn 5

您没有从上下文管理器协议__enter__指定的方式返回对象.添加到方法的末尾.return self__enter__