我正在移植一些 Python 2 遗留代码并且我有这个类:
class myfile(file):
"Wrapper for file object whose read member returns a string buffer"
def __init__ (self, *args):
return file.__init__ (self, *args)
def read(self, size=-1):
return create_string_buffer(file.read(self, size))
它像 File 对象一样使用:
self._file = myfile(name, mode, buffering)
self._file.seek(self.si*self.blocksize)
我正在尝试像这样在 Python 3 中实现它:
class myfile(io.FileIO):
"Wrapper for file object whose read member returns a string buffer"
def __init__(self, name, mode, *args, **kwargs):
super(myfile, self).__init__(name, mode, closefd=True, *args, **kwargs)
def read(self, size=-1):
return create_string_buffer(self.read(size))
问题是 FileIO 的构造函数不接受 buffering
参数,Python 抛出一个 TypeError: fileio() takes at most 3 arguments (4 given)
错误。
Python 3 open function是我需要的。我可以继承吗?我看过 PyFile_FromFd class ,但它需要一个打开的文件描述符,我担心行为不会相同。
谢谢!!!
最佳答案
您不能继承open
。缓冲参数更改返回的类,因此 open
被实现为可以返回多个类之一的函数。最好的选择是做同样的事情,必要时使用您自己的包装器类。
基本实现思路是:
myfile
是一个函数,其签名类似于open
- 您有两个类,一个继承自
FileIO
,一个继承自BufferedReader
。 - 当调用
myfile
时,它会检查buffering
参数,然后创建并返回FileIO
派生子类(未缓冲时)或创建带有open
的普通无缓冲FileIO
类,然后将其包装在您的BufferedReader
派生子类中。
关于python - 将 Python2 文件派生类移植到 Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63815087/