[Tutor] class question
Gregor Lingl
glingl@aon.at
Thu, 31 Jan 2002 09:14:50 +0100
Dear Frank!
> I have a question concerning one of the class examples given in O'Reilly's
> book "Learning Python"
>
> the following example is given:
>
> >>>class adder:
> def __init__(self, value=0):
> self.data=value #initialize data
> def __add__(self, other):
> self.data=self.data + other #add other in-place
> def __repr__(self):
> return `self.data` #convert to string
> ...
> ...
> >>>x=adder(1) #__init__
> >>>x=2; x=2 #__add__
> >>>x #__repr__
> 5
>
This certainly is a typo!
It should read:
>>> x = adder(1)
>>> x+2; x+2
>>> x
5
>>>
which is equivalent to
>>> x = adder(1)
>>> x+2
>>> x+2
>>> x
5
>>>
>>> x+2
is a call of the __add__()-method of the adder-object x
so it changes the x.data first to 3 then to 5
The last statement
>>> x
is a call of x.__repr__() and produces a printable representation
of x.data, i. e. 5 (in this case).
Because of the lack of a return-statement in __add__()
(a somewhat strange feature) the statement x+2 returns None
and you cannot use
>>> x = x+2
as one would expect.
Hope that helps
Gregor