如何获取一个类似于 open() 返回的文件对象的对象,并且还包含我自己定义的方法以及 read()、write()、tell() 等?

问题描述 投票:0回答:1

考虑这段代码:

fileA = open("filename", "r")
fileA.read(34) #works as normal
fileA.READ() #doesn't work because READ member not defined (i assume it's not defined), but I want this to work in the way I code this new READ method

由于

READ
不起作用,因此我想创建新方法
OPEN
,其中
open
是我的文件,并返回新类类型的文件对象,其中包括
READ
作为其成员(以及所有其他成员)方法如
write
read
tell
seek
等)。

fileB = OPEN("filename", "r")
fileB.READ(44)  #should work as I would define it
fileB.read(34)  #should work as it would work for fileA.read() in first example
fileB.write(somestring) #should work  

可以这样做吗?如果是的话,怎么办?

python file class inheritance file-handling
1个回答
0
投票

正如评论之一所述,没有用于打开文件的低级 API;所以你被迫使用

open
。但是,可以在 python 中对文件对象进行子类化。在 python 中,由
open
生成的文件通常是
TextIOWrapper
的实例。可以通过在 python 交互模式下运行以下两行来发送短信。

$: python -i
>>> from io import TextIOWrapper
>>> type(open("Book2.csv"))==TextIOWrapper # returns True

可以从

io
模块访问该类,它允许我们创建自定义子类,您可以在其中定义所需的任何方法。然后,您可以从文件对象中提取所有参数并将它们传递到您的自定义子类中。这是我相信您想要实现的目标的模板代码。

from io import TextIOWrapper
from typing import override


class MyWrapper(TextIOWrapper):
    __slots__=['_instance'] # prevents the file from closing
    
    @override
    def close(self):
        """ensure instance closes properly"""
        self._instance.close()
        return super().close()    

    @classmethod
    def OPEN(cls,file, mode = "r", **kwargs):
        """
        Based on `open`
        """
        return cls.wrap_file(open(file,mode,**kwargs))

    @classmethod
    def wrap_file(cls,file):
        """
        This method turns a file produced by `open`
        into an instance of `MyWrapper`
        """
        newline:str|None = None
        if isinstance(file.newlines,tuple):
            newline = file.newlines[0]
        else:
            newline = file.newlines
        ret = cls(buffer=file.buffer,encoding=file.encoding,
                   errors=file.errors,line_buffering=file.line_buffering,
                   write_through=file.write_through, newline=newline)
        ret._instance = file
        return ret

    def READ(self):
        """
        Your custom implementation of read.
        
        Additional stuff you want in you implementation.
        """
        return super().read().upper() # arbitrary exaplme

OPEN
调用
open
方法,该方法创建打开的文件,然后将其传递到并返回
wrap_file
wrap_file
从实例强制文件对象
MyWrapper
READ
执行您定义的任何操作。

© www.soinside.com 2019 - 2024. All rights reserved.