弃用警告:object.__init__() 不带参数

DeprecationWarning: object.__init__() takes no parameters

我已经搜索过了,但无法完全找到答案。我想要一个来自 sympy 的具有特定维度的 Matrix 的简单子类。当我 运行 这个代码在 python 2.7:

from sympy import *
class JVec(Matrix):
    def __init__(self, *args):
        super(JVec,self).__init__(*args)
        #Matrix.__init__(self, *args)
        if self.shape != (2,1):
            raise TypeError("JVec: shape must be (2,1)")
a = JVec([1,0])

我收到错误消息

/Users/me/anaconda/lib/python2.7/site-packages/ipykernel/__main__.py:4: 
DeprecationWarning: object.__init__() takes no parameters

无论我按原样使用代码,还是替换我注释掉的行中的 __init__,我都会得到同样的错误。

我可以将消息作为 error 使用:

>>> class Foo(object):
...    def __init__(self,*args):
...        super(Foo,self).__init__(*args)
... 
>>> Foo()
<__main__.Foo object at 0xb744370c>
>>> Foo('one')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: object.__init__() takes no parameters

这不完全是您的问题,但可能会提供有关如何进一步挖掘的想法。

问题是因为调用 super(JVec,self).__init__(*args) 会找到 object 定义的 __init__ 因为基数 类 都没有定义 __init__方法。

sympy 的代码正在使用 a different mechanism 创建新实例。您应该将函数重写为:

class JVec(Matrix):
    def __new__(cls, *args):
        newobj = Matrix.__new__(cls, *args)
        if newobj.shape != (2, 1):
            raise TypeError("JVec: shape must be (2,1)")
        return newobj

这是基于他们的方式 creating the RayTransferMatrix instances