无法引用其他内部方法利用自身 - python 3.6

Cannot refer to other within method utilizing self - python 3.6

我一直在研究这个问题,但我似乎无法理解它的 add() 部分。如果有人可以帮助我并向我解释,将不胜感激。特别是其他参数。实际问题在方法的文档字符串中。我相信 str(self): 方法是正确的并且 init(self,m,b ) 方法也正确,但如果不正确,请纠正我。

class LinearPolynomial():
    def __init__(self, m, b):
        self.m = m
        self.b = b

    def __str__(self):
        """
        Returns a string representation of the LinearPolynomial instance
        referenced by self.

        Returns
        -------
        A string formatted like:

        mx + b

        Where m is self.m and b is self.b
        """
        string= '{}x + {}'
        return string.format(self.m,self.b)

    def __add__(self, other):
        """
        This function adds the other instance of LinearPolynomial
        to the instance referenced by self.

        Returns
        -------
        The sum of this instance of LinearPolynomial with another
        instance of LinearPolynomial. This sum will not change either
        of the instances reference by self or other. It returns the
        sum as a new instance of LinearPolynomial, instantiated with
        the newly calculated sum.
        """
        Cm= other.m + self.m
        Cb = other.b + self.b
        string= '{}x + {}'
        return string.format(Cm,Cb)

预期结果在方法的文档字符串中。

您需要创建并 return 一个新的 LinearPolynomial 对象,而不是字符串。您的方法还应该检查其他操作数的类型和 return NotImplemented 值(如果它不是 LinearPolynomial

def __add__(self, other):
    if not isinstance(other, LinearPolynomial):
        return NotImplemented
    Cm = other.m + self.m
    Cb = other.b + self.b
    return LinearPolynomial(Cm, Cb)