Python的`with`语句目标意外为None
看起来我对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
,那么你就能得到你想要的输出。