Kyl*_*ong 3 python with-statement code-inspection contextmanager
我已经读过,每次使用'with'时都会调用对象的__ enter __()和__ exit __()方法.我理解,对于用户定义的对象,您可以自己定义这些方法,但我不明白它如何适用于内置对象/函数,如"open"甚至是测试用例.
此代码按预期工作,我假设它使用__ exit __()关闭文件:
with open('output.txt', 'w') as f:
f.write('Hi there!')
Run Code Online (Sandbox Code Playgroud)
要么
with self.assertRaises(ValueError):
remove_driver(self.driver) # self refers to a class that inherits from the default unittest.TestCase
Run Code Online (Sandbox Code Playgroud)
然而,当我检查它时,对任一对象都没有__ enter __()或__ exit __()方法:
那么'开放'如何与'同时'合作?不应该支持上下文管理协议的对象__输入__()和__ exit __()方法定义和检查吗?
zon*_*ndo 10
open()是一个功能.它返回一个有__enter__和__exit__方法的东西.看看这样的事情:
>>> class f:
... def __init__(self):
... print 'init'
... def __enter__(self):
... print 'enter'
... def __exit__(self, *a):
... print 'exit'
...
>>> with f():
... pass
...
init
enter
exit
>>> def return_f():
... return f()
...
>>> with return_f():
... pass
...
init
enter
exit
Run Code Online (Sandbox Code Playgroud)
当然,return_f它本身没有那些方法,但它返回的是什么.
open是一个使用上下文方法返回文件对象的函数,并且self.assertRaises是一个使用上下文方法返回对象的方法,尝试检查dir它们的返回值:
>>> x = open(__file__, "r")
>>> x
<_io.TextIOWrapper name='test.py' mode='r' encoding='US-ASCII'>
>>> type(x)
<class '_io.TextIOWrapper'>
>>> "__exit__" in dir(x)
True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1368 次 |
| 最近记录: |