将python2'file'类的子类移植到python3 [英] Porting a sub-class of python2 'file' class to python3

查看:175
本文介绍了将python2'file'类的子类移植到python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用class TiffFile(file)的旧代码. python3调用它的方式是什么?

I have a legacy code that calls class TiffFile(file). What is the python3 way to call it?

我尝试在python2中替换以下内容:

I tried to replace following in python2:

class TiffFile(file):
    def __init__(self, path):
        file.__init__(self, path, 'r+b')

在python3中通过此方式

By this in python3:

class TiffFile(RawIOBase):
    def __init__(self, path):
        super(TiffFile, self).__init__(path, 'r+b')

但是现在我得到了TypeError: object.__init__() takes no parameters

推荐答案

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一样,也可以在

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.

这篇关于将python2'file'类的子类移植到python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆