python-3.x - 将继承 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 类型的参数)?
提前致谢!
解决方案
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 中都适用于我
推荐阅读
- c++ - 在Qt中实时获取cmd命令的输出
- python - 键入:TypeVar 与 Union,mypy 错误:缺少泛型类型的类型参数
- ios - iOS 本地主机 RTMP 服务器
- dart - Dart 读取大文件同步
- docker - 为什么 docker hub 上的某些存储库没有 dockerfile?
- javascript - 如何用玩笑模拟 es6 构造函数
- php - 为什么输入不去本地主机?
- amazon-web-services - 每个 AZ 中没有目标的 AWS 网络负载均衡器
- php - 如何计算 PHP 数组中的真值和假值?
- c# - 批量删除是在 Azure 存储中执行目录删除的更好方法吗?