在 with_statement 中使用实例时出现问题

发布于 2024-07-12 11:12:05 字数 759 浏览 9 评论 0原文

最近开始学习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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍风燃霜 2024-07-19 11:12:05

您的 __enter__ 方法需要返回应用于 with 语句的“as g”部分的对象。 请参阅文档,其中指出:

  • 如果 with 语句中包含目标,将 __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:

  • If a target was included in the with statement, the return value from __enter__() is assigned to it.

Currently, it has no return statement, so g gets bound to None (the default return value)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文