Search code examples
python-3.xmethodsself

Cannot refer to other within method utilizing self - python 3.6


I have been going at this question and i cant seem to wrap my head around the add() portion of it. if any one could help me out and explain it to me that would be much appreciated. especially with the other parameter. The actual question is within the Docstring of the methods. I beleive the str(self): method is correct and the init(self,m,b) method is correct also but if not please correct me.

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)

The expected results are within the docstring of the methods.


Solution

  • You need to create and return a new LinearPolynomial object, not a string. Your method should also check the type of the other operand and return the NotImplemented value if it is not a 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)