【问题标题】:Trying to figure out how the 'with..as' construct works in python试图弄清楚'with..as'结构在python中是如何工作的
【发布时间】:2014-04-27 09:58:52
【问题描述】:

我正在尝试学习 python,我登陆了

与..as

construct,使用如下:

with open("somefile.txt", 'rt') as file:
    print(file.read()) 
    # at the end of execution file.close() is called automatically.

因此,作为一种学习策略,我尝试执行以下操作:

class Derived():

    def __enter__(self):
        print('__enter__')

    def __exit__(self, exc_type, exc_value, traceback):
        print('__exit__')

with  Derived() as derived:
    print(derived)

我得到了这个输出:

__enter__
None
__exit__

我的问题是:

  • 为什么print(derived) 返回的是None 对象而不是Derived 对象?

【问题讨论】:

  • __enter__ 必须返回绑定到dervied 的对象。

标签: python


【解决方案1】:

名称derived 绑定到__enter__ 方法返回的对象,即None。试试:

def __enter__(self):
    print('__enter__')
    return self

Docs:

object.__enter__(self)

输入与该对象相关的运行时上下文。 with 语句会将此方法的返回值绑定到该语句的as 子句中指定的目标(如果有)。

【讨论】:

  • 我到处看了看,却没能在任何地方读到这个?我怎么可能想出来的?是否有任何地方解释此要求的手册?
  • @Kam 更新了文档参考
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多