在哪里定义了Python内置对象的优enter_优()和uu exit_uu()?

2024-05-16 03:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过,每次使用“with”时都会调用该对象的enter和exit_u;()方法。我知道对于用户定义的对象,您可以自己定义这些方法,但我不明白这对于内置的对象/函数(比如“open”甚至testcases)是如何工作的。在

这段代码如预期的那样工作,我假设它使用UuuExit_Uu9()关闭文件:

with open('output.txt', 'w') as f:
    f.write('Hi there!')

或者

^{pr2}$

但是,当我检查这两个对象时,它都没有这样的方法:

enter image description here

enter image description here

那么“open”和“with”是如何工作的呢?支持上下文管理协议的对象不应该定义并可检查的UuuEnter_2;()和UuExit_Uu()方法吗?在


Tags: 文件对象方法函数代码用户定义with
3条回答

open是一个使用context方法返回file对象的函数,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

您要检查的是open函数本身还是assertRaises方法本身是否有__enter__和{}方法,这时您应该查看返回值有哪些方法。在

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

当然,return_f本身没有这些方法,但它返回的却是这些方法。在

相关问题 更多 >