[Tutor] return class-call or value

Magnus Lycka magnus@thinkware.se
Fri Dec 20 07:37:01 2002


At 10:26 2002-12-20 +0800, Wong Zhee Shiong wrote:
>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?

No you don't.

In the first case you return an instance of the P class,
which has all the properties and behaviour of that class.
In the second case you return a tuple. That tuple doesn't
have those qualities at all.

But your class is rather abstract, so it might be difficult
to see the difference. Let's play with an unfinished Money
class instead.

 >>> class Money:
...     def __init__(self, cur, val):
...             self.cur = cur
...             self.val = float(val)
...     def __str__(self):
...             return "%s %.2f" % (self.cur, self.val)
...     def __add__(self, other):
...             assert self.cur == other.cur, "Currency conversion not 
implemented"
...             return self.__class__(self.cur, self.val + other.val)
...
 >>> a, b, c = Money('$', 5), Money('$', 7.5), Money('SEK', 1400.5)
 >>> print a, b, c
$ 5.00 $ 7.50 SEK 1400.50
 >>> x = a+b
 >>> print x
$ 12.50
 >>> x = a+c
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 8, in __add__
AssertionError: Currency conversion not implemented

If __add__ had returned self.val + other.val instead of creating a
new Money instance, x whould have been a float, not a Money object.
It would no longer have a currency, or a way to print itself in a
pretty way.



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se