似乎我对pythonwith语句不了解。
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>。但是我什么都 没有 。
这有什么问题吗?任何建议都会有所帮助。
(我正在使用Python 2.6.6。)
编辑:
感谢ephement向我指出了文档。该__enter__方法应阅读
__enter__
def __enter__(self): return self
从with文档中:
如果with语句中包含目标,则将__enter__()为其分配返回值。
__enter__()
如果是def __enter__(self): return self,那么将产生预期的输出。