题
我最近开始学习蟒蛇,我到了 与 发言。我试着用它与一个类实例,但我想我做错了什么。这里是代码:
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()
事情是,当解释器到达 "确定" 方法内,有发言,下面的例外是提出:
Traceback (most recent call last):
File "dec.py", line 23, in
g.ok()
AttributeError: 'NoneType' object has no attribute 'ok'
为什么克对象具有类型NoneType?我如何可以使用的一个实例 与 发言?
解决方案
你的 __enter__
方法需要回报的对象,应当使用"as g
"一部分的所有声明。看看 文档, ,其它国家:
- 如果一个目标是包括在与声明,返回值
__enter__()
分配给它。
目前,它没有返回的声明,因此g得到开 None
(default return value)
不隶属于 StackOverflow