TypeError:+的不支持的操作数类型:'多项式'和多项式'

时间:2017-12-04 15:38:31

标签: python typeerror polynomial-math

我真的不知道如何解决错误。

不起作用的函数是sumPolynoms,multiplyPolynoms和raisePolynomial。 Domain.Polynom是第二个。

import numpy as np
from Domain.Polynom import Polynomial
from numpy.polynomial import polynomial as P

class PolyOperations:
    def getDerivation(self,p):
        polyNumpyRepresentation=p.getRepresentation()
        derivation=np.polyder(polyNumpyRepresentation)
        return derivation
    def getValueOfPolynomial(self,p,x):
        polyRepresentation=p.getRepresentation()
        return np.polyval(polyRepresentation,x)
    def sumPolynoms(self,p,q):
        return np.polyadd(p,q)
    def multiplyPolynoms(self,p,q):
        return P.polymul(p,q)
    def raisePolynomial(self,p,y):
        return self.np.polypow(p,y)
class Polynomial:
    def __init__(self,coeficienti):
        self.__coeficienti=coeficienti
    def getCoefficients(self):
        return self.__coeficienti
    def addCoefficients(self,coef):
        self.__coefficients.append(coef)
    def getRepresentation(self):
        return np.poly1d(self.getCoefficients())

1 个答案:

答案 0 :(得分:0)

错误表示您传递给p的对象qdef sumPolynoms(self, p, q)不会overload operator +

>>> class A:
...   pass
... 
>>> a = A()
>>> a + a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'A' and 'A'

我只能推测您的Polynomial类是如何定义的,但它至少需要__add__方法:

class Polynomial:

    def __init__(self, np_array):
        self.data = np_array

    def __add__(self, other_polynomial):
        return Polynomial(self.data + other_polynomial.data)

或类似的东西。 multiplyPolynomsraisePolynomial可能会抱怨缺少不同的操作,因此他们可能需要__mul____pow__操作。

或者,您可以更改sumPolynoms本身:

def sumPolynoms(self, p, q):
    numpy_array_from_p = p.some_attribute
    numpy_array_from_q = q.some_attribute
    return np.polyadd(numpy_array_from_p, numpy_array_from_q)