看源代码。当用r模式初始化时,read()方法会报错,但不是所有方法会报错。更令人困惑的是 fo.read 和fo1.read 类型是一样的。
import _io # import io
class FO(_io.TextIOWrapper): # (io.TextIOWrapper)
def __init__(self, buffer):
super().__init__(buffer) # supper(FO,self)
fo=FO(open('test.txt','rb'))
print(fo.tell()) #
print(fo.read) #
print(fo.read())
fo1=FO(open('test.txt','r'))
print(fo1.tell()) # 没报错
print(fo1.read) # 没报错
print(type(fo1.read)==type(fo.read)) # True
print(fo1.read()) # 报错
报错信息如下:
Traceback (most recent call last):
File "D:\Python\mytest\cls.py", line 81, in <module>
print(fo1.read()) # 报错
TypeError: 'str' does not support the buffer interface
那么,文件对象怎么继承?
我试过了,这样是可以的。只是不能关闭f。
f=open('test.txt','r')
fo=File(f.buffer)
就是这样继承的啊,继承只不过是在外面多封装一层而已,本质上还是操作原来的buffer,所以f是肯定不能关闭的,而且我觉得这样写更好:
class File(io.TextIOWrapper):就是把关闭f写到继承的类里去了。
追问为什么要重写close.既然已经继承了,直接fo.colse()不也可以吗?