首页 > 解决方案 > 将继承 str 和 __new__ 的类从 py 2 迁移到 2/3

问题描述

我目前正在尝试将一些 python 2 代码迁移到 python 2/3 兼容代码,并且遇到了这个特定类的问题:

class FileID(str):
    def __new__(cls, fileid, *args):
        return super(FileID, cls).__new__(cls, fileid)

    def __init__(self, fileid, size):
        super(FileID, self).__init__(fileid)
        self.size = size

x = FileID('a', 1)

print(x) # prints: a
print(x.size) # prints: 1

在 python 2.7 中,这工作得很好。

要移植过来,我一直在使用from builtins import super.

对于 python 3.6,我删除了多余的内部超级参数,但它似乎对__new__方法和传入int参数都犹豫不决(说它必须是str)。

有没有办法将此类创建为等效的 py2/3 (继承str,并且可以接受 int 类型的参数)?

提前致谢!

标签: python-3.xpython-2.7inheritance

解决方案


class FileID(str):
    def __new__(cls, fileid, *args):
        return super().__new__(cls, fileid)
    def __init__(self, fileid, size):
        super().__init__()
        self.size = size
x = FileID('a', 1)
print(x) # prints: a
print(x.size) # prints: 1

在 python 2 和 3 中都适用于我


推荐阅读