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)
我期望一些输出,如
这里有什么问题吗?任何建议都会有所帮助。
(我正在使用 Python 2.6.6。)
编辑:
感谢 ephemment 为我指明了文档。 __enter__
方法应为
def __enter__(self): return self
seems like I do not understand something with---the python with
statement.
Consider this class:
class test(object):
def __enter__(self): pass
def __exit__(self, *ignored): pass
now, when using it with with
, like in
with test() as michael:
print repr(michael)
I would expect some output like <test instance at memore blah>. But I get None.
Something wrong here? Any suggestions would help.
(I am using Python 2.6.6.)
EDIT:
Thanks to
ephement for pointing me to the documentation. The __enter__
method should read
def __enter__(self): return self
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自
with
文档:如果您
def __enter__(self): return self
,则会产生您预期的输出。From the
with
documentation:If you
def __enter__(self): return self
, then your expected output is produced.来自文档:
From the docs:
我对
repr(michael)
得到同样的结果,试试这个:
我不完全确定,但我认为这与您尚未定义
<
方法test
类中的strong>reprI get the same thing for
repr(michael)
Try this instead:
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 yourtest
class