[Tutor] return class-call or value

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu Dec 19 22:33:03 2002


On Fri, 20 Dec 2002, Wong Zhee Shiong wrote:

> >>>class P:
> ...    def __init__(self, p1, p2):
> ...        self.dat=(p1,p2)
> ...    def __add__(self,other):
> ...        return self.__class__(self.dat[0] + other.dat[0], \
> ...                              self.dat[1] + other.dat[1])
> ...        # or perhaps "return P(...)"
> ...
> If I replace the return statement with a value, i.e.
>      return (self.dat[0] + other.dat[0], self.dat[1] + other.dat[1])
>
> I still get the same result for
>
>    p = P(1,1)
>
> as before replacement, but what do I miss (wrong) about returning a
> value in OOP sense?


Hello!

Make sure that you're actually testing the thing that you changed.
*grin*

You need to test to see how your change affected the adding of these P
instances; you didn't notice a difference because your test was checking
to see if the initializer of your class is still working.

*** spoiler space ahead ***









*** spoiler space ***

Actually, to really be rigorous, try adding three P instances together:
you should definitely notice a difference in the behavior of the code,
depending on what kind of thing the __add__ function returns.

The thing that you're tinkering with is related to the mathematical idea
of "closure":

    http://mathworld.wolfram.com/SetClosure.html

where we can say that "+" is our binary operator that acts on two P
elements.


Good luck to you!