使用with_statement中的实例的问题

Geo*_*Geo 4 python with-statement

我最近开始学习Python,和我达成了声明.我试图将它与类实例一起使用,但我认为我做错了.这是代码:


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()
Run Code Online (Sandbox Code Playgroud)

问题是,当解释器到达with语句中的ok方法时,会引发以下异常:


Traceback (most recent call last):
  File "dec.py", line 23, in 
    g.ok()
AttributeError: 'NoneType' object has no attribute 'ok'
Run Code Online (Sandbox Code Playgroud)

为什么g对象的类型为NoneType?如何在with语句中使用实例?

Bri*_*ian 12

您的__enter__方法需要返回应该用于as gwith语句的" "部分的对象.请参阅文档,其中说明:

  • 如果目标包含在with语句中,__enter__()则会为其分配返回值.

目前,它没有return语句,所以g绑定到None(默认返回值)