[Tutor] class question
alan.gauld@bt.com
alan.gauld@bt.com
Thu, 31 Jan 2002 17:21:37 -0000
> >>>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
So adding updates the internal value, see below...
> def __repr__(self):
> return `self.data` #convert to string
> ...
> ...
> >>>x=adder(1) #__init__
> >>>x=2; x=2 #__add__
Assuming x=2 should be x+2....
This adds 2 to x twice, so after the first time x=3,
then second time round x = 5
> >>>x #__repr__
> 5
Which is what we see here.
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld