且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将python2'file'类的子类移植到python3

更新时间:2023-10-27 18:55:16

RawIOBase.__init__ 不带任何参数,这就是错误所在.

RawIOBase.__init__ does not take any arguments, that is where you error is.

您的TiffFile实现还继承了 file 不是一个类,而是一个构造函数,因此您的Python 2实现是非惯用的,甚至有人认为它是错误的.您应该使用open而不是file,并且在类上下文中,应该将io模块类用于输入和输出.

Your TiffFile implementation also inherits file which is not a a class, but a constructor function, so your Python 2 implementation is non-idiomatic, and someone could even claim it is wrong-ish. You should use open instead of file, and in a class context you should use an io module class for input and output.

您可以使用 open 返回要使用的文件对象,就像在Python 2.7中使用file一样,也可以在 Python 3 用于访问文件流,就像使用open一样.

You can use open to return a file object for use as you would use file in Python 2.7 or you can use io.FileIO in both Python 2 and Python 3 for accessing file streams, like you would do with open.

所以您的实现将更像:

import io

class TiffFile(io.FileIO):
    def __init__(self, name, mode='r+b', *args, **kwargs):
        super(TiffFile, self).__init__(name, mode, *args, **kwargs)

这应该可以在当前所有受支持的Python版本中使用,并允许您使用与以前的实现相同的界面,同时更加正确和可移植.

This should work in all currently supported Python versions and allow you the same interface as your old implementation while being more correct and portable.

您是否真的使用r+b在Windows上以读写二进制模式打开文件?如果您不写文件,而只是读取TIFF数据,则可能应该使用rb模式. rb将以二进制模式打开文件,以供只读.附加的+设置文件以读写模式打开.

Are you actually using r+b for opening the file in read-write-binary mode on Windows? You should probably be using rb mode if you are not writing into the file, but just reading the TIFF data. rb would open the file in binary mode for reading only. The appended + sets the file to open in read-write mode.