我最近开始学习 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语句的实例?