|
本帖最后由 asii2018 于 2018-10-17 22:01 编辑
刚接触python 自学了一段时间 使用pycharm ide 在练习with as时有个疑问
with open('TestDict.py','r') as fileDict: //
print(type(fileDict))
print("fileDict line count = ",fileDict.readlines().__len__())
输出如下:
<class '_io.TextIOWrapper'>
fileDict line count = 9
背景:
with as 的语法是需要定义__enter__ 和 __exit__才会自动执行
所以我猜测 应该在open打开的流的父类中可以找到 enter和exit方法 里面有打开文件和关闭文件的定义
于是我找到TextIOWrapper 没有定义 他的父类io.TextIOBase 没有定义
_io._TextIOBase中没有定义 _TextIOBase没有定义
_IOBase中有写enter和exit方法 但是pass?
def __enter__(self, *args, **kwargs): # real signature unknown
pass
def __exit__(self, *args, **kwargs): # real signature unknown
pass
why?
后来发现竟然有三个TextIOWrapper 分别来自与 io.py _io.py _pyio.py
最终在_pyio.py中找到close和open的实现def __enter__(self):
# That's a forward reference
"""Context management protocol. Returns self (an instance of IOBase)."""
self._checkClosed()
return self
def __exit__(self, *args):
"""Context management protocol. Calls close()"""
self.close()
疑问:
1.为什么ide引导我去看<class '_io.TextIOWrapper'> _io模块的TextIOWrapper? 而不是直接_pyio模块的?
2.io.py _io.py _pyio.py这三个模块有什么关联?他们的关联定义在哪个文件?
|
|