python - 为什么 *args 不能从覆盖 int 的类传递给 super().__init__()?
问题描述
class MyInt(int):
def __new__(cls, *args, **kwargs):
print(repr(args), repr(kwargs))
return super(MyInt, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print(repr(args), repr(kwargs))
return super(MyInt, self).__init__(*args, **kwargs)
MyInt(1)
此代码输出:
(1,) {}
(1,) {}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-a45744cab1af> in <module>()
----> 1 MyInt(1)
<ipython-input-3-a38fc9aae2fe> in __init__(self, *args, **kwargs)
5 def __init__(self, *args, **kwargs):
6 print(repr(args), repr(kwargs))
----> 7 return super(MyInt, self).__init__(*args, **kwargs)
8
TypeError: object.__init__() takes no parameters
似乎基地__init__()
正在期待 args,因为我可以打印它们。那么为什么我不能将它们传递给基类的方法呢?(顺便说一句,这在 python 2.7 中运行良好)
解决方案
由于int
对象是不可变的,因此您不能使用该__init__
方法。正如本文档中所述,您只需使用__new__
.
在这里,__init__
当您创建一个新的时,它会优先考虑该方法MyInt
,这就是您收到错误的原因。因此,只需取消该__init__
方法并保留该方法即可__new__
。
希望我有用。
推荐阅读
- json - 在 Node-Red 中合并两个 JSON 对象
- swift - SwiftUI:更改 ZStack .zIndex 顺序
- vue.js - NuxtJs SSR 配置
- bash - 大括号扩展为单个参数
- ansible - 如何处理失败并使用 WHEN 传递 ansible 消息
- vue.js - 使用 @theme 将默认主题中的组件定位为在自定义组件中使用
- java - 如何将 javafx(前端)连接到休眠(后端)
- json - SwiftUI:使用 Text() 而不是 List 显示 JSON 数据
- mysql - 当两个行号相同时选择值
- ubuntu-18.04 - 我搞砸了我的 Steam 安装,如何修复损坏的软件包?