在 with_statement 中使用实例时出现问题
最近开始学习python,就到了with语句。 我尝试将它与类实例一起使用,但我认为我做错了。 代码如下:
from __future__ import with_statement
import pdb
class Geo:
def __init__(self,text):
self.text = text
def __enter__(self):
print "entering"
def __exit__(self,exception_type,exception_value,exception_traceback):
print "exiting"
def ok(self):
print self.text
def __get(self):
return self.text
with Geo("line") as g :
g.ok()
问题是,当解释器到达 with 语句内的 ok 方法时,会引发以下异常:
Traceback (most recent call last):
File "dec.py", line 23, in
g.ok()
AttributeError: 'NoneType' object has no attribute 'ok'
为什么 g 对象的类型为 NoneType? 如何通过 with 语句使用实例?
I've recently started to learn python , and I reached the with statement . I've tried to use it with a class instance , but I think I'm doing something wrong . Here is the code :
from __future__ import with_statement
import pdb
class Geo:
def __init__(self,text):
self.text = text
def __enter__(self):
print "entering"
def __exit__(self,exception_type,exception_value,exception_traceback):
print "exiting"
def ok(self):
print self.text
def __get(self):
return self.text
with Geo("line") as g :
g.ok()
The thing is that when the interpreter reaches the ok method inside the with statement , the following exception is raised :
Traceback (most recent call last):
File "dec.py", line 23, in
g.ok()
AttributeError: 'NoneType' object has no attribute 'ok'
Why does the g object have the type NoneType ? How can I use an instance with the with statement ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
__enter__
方法需要返回应用于 with 语句的“as g
”部分的对象。 请参阅文档,其中指出:__enter__()
的返回值赋给它。目前,它没有 return 语句,因此 g 绑定到
None
(默认返回值)Your
__enter__
method needs to return the object that should be used for the "as g
" part of the with statement. See the documentation, where it states:__enter__()
is assigned to it.Currently, it has no return statement, so g gets bound to
None
(the default return value)