Python的`with`语句目标意外为None

13 投票
3 回答
5063 浏览
提问于 2025-04-16 10:50

看起来我对Python的with语句有点不太明白。

考虑这个类:

class test(object):
    def __enter__(self): pass
    def __exit__(self, *ignored): pass

现在,当我用with来使用它,比如在

with test() as michael:
    print repr(michael)

我本来期待能看到一些像<test instance at memore blah>这样的输出。但我得到的是None

这里有什么问题吗?任何建议都很有帮助。

(我使用的是Python 2.6.6。)

编辑:

感谢ephement指引我去查阅文档。__enter__方法应该是这样的:

    def __enter__(self): return self

3 个回答

-1

我在使用 repr(michael) 时也得到了同样的结果。

你可以试试这个:

m.__repr__()

我不是很确定,但我觉得这可能和你在 test 类里没有定义 repr 方法有关。

2

来自文档

object.__enter__(self)

进入与这个对象相关的运行时环境。如果有的话,with语句会把这个方法的返回值绑定到语句中as部分指定的目标上。

19

来自with文档的内容:

如果在with语句中包含了一个目标,那么__enter__()的返回值会被赋值给这个目标。

如果你写了def __enter__(self): return self,那么你就能得到你想要的输出。

撰写回答