13

好像我不明白 --- pythonwith语句。

考虑这个类:

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
4

3 回答 3

19

with文档中:

with如果语句中包含目标,则将返回值 from__enter__()分配给它。

如果你def __enter__(self): return self,那么你的预期输出产生。

于 2011-01-29T07:03:25.657 回答
2

文档

object.__enter__(self)

Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

于 2011-01-29T07:03:55.767 回答
-1

I get the same thing for repr(michael)

Try this instead:

m.__repr__()

I'm not entirely sure, but I think it has something to do with the fact that you haven't defined the repr method in your test class

于 2011-01-29T07:06:40.763 回答