首页 > 解决方案 > 为什么 *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 中运行良好)

标签: pythonpython-3.xconstructorint

解决方案


由于int对象是不可变的,因此您不能使用该__init__方法。正如本文档中所述,您只需使用__new__.

在这里,__init__当您创建一个新的时,它会优先考虑该方法MyInt,这就是您收到错误的原因。因此,只需取消该__init__方法并保留该方法即可__new__

希望我有用。


推荐阅读