Python 文件对象继承问题

看源代码。当用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

TextIOWrapper要求的参数buffer是bytes,'r'打开的是str而不是bytes当然会出错。
fo.read和fo1.read都是一个方法而已,它们的type当然会相同,那type(fo.read) is type(fo.write)是不是更令你困惑了。。。
另外,你的这个问题和继承没啥关系吧,完全是概念问题。。追问

那么,文件对象怎么继承?
我试过了,这样是可以的。只是不能关闭f。
f=open('test.txt','r')
fo=File(f.buffer)

追答

就是这样继承的啊,继承只不过是在外面多封装一层而已,本质上还是操作原来的buffer,所以f是肯定不能关闭的,而且我觉得这样写更好:

class File(io.TextIOWrapper):
    def __init__(self, filename, mode):
        self.file_obj = open(filename, mode)
        super().__init__(self.file_obj.buffer)
    
    def close(self):
        self.file_obj.close()
        super().close()

fo = File('test.txt', 'r')

就是把关闭f写到继承的类里去了。

追问

为什么要重写close.既然已经继承了,直接fo.colse()不也可以吗?

温馨提示:答案为网友推荐,仅供参考
相似回答