[Tutor] special class methods
Sean 'Shaleh' Perry
shalehperry@attbi.com
Wed, 05 Jun 2002 17:51:58 -0700 (PDT)
On 05-Jun-2002 Cameron Stoner wrote:
> Hi all,
>
> Why would you want to use the __add__ special class method in a class? I
> know what it is soposed to do, but can't you just add two objects together.
> I read somewhere that in Python everything is an object. So having a special
> class method used to add objects seem to be redundant to me. Is this true?
>
when you define __add__ (or its brothers) the interpreter calls them when you
use the respective symbols.
so:
>>> class Foo:
... def __init__(self, v = 5):
... self.value = v
... def __add__(self, other):
... return self.value * other.value
...
>>> a = Foo(3)
>>> b = Foo(7)
>>> a + b
21 # not 10
yes, this is a silly example. But you define how the class acts with the math
ops by defining the equivalent function.
A more useful example would be something like:
class Rational:
def __init__(self, top, bottom):
self.numerator = top
self.denominator = bottom
def __add__(self, other):
# do common denominator math then add the two numbers and reduce
then you could do:
a = Rational(1,2) # 1/2
b = Rational(2,3) # 2/3
c = a + b # 3/6 + 4/6 => 7/6
or
a = Rational(1,3)
b = Rational(1,6)
c = a + b # 2/6 + 1/6 => 3/6 => 1/2