小编典典

python的`with`语句目标意外地是None

python

似乎我对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>。但是我什么都 没有

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

(我正在使用Python 2.6.6。)

编辑:

感谢ephement向我指出了文档。该__enter__方法应阅读

    def __enter__(self): return self

阅读 151

收藏
2021-01-20

共1个答案

小编典典

with文档中:

如果with语句中包含目标,则将__enter__()为其分配返回值。

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

2021-01-20