classes

Zero Piraeus schesis at gmail.com
Wed Oct 24 11:14:26 EDT 2012


:

On 24 October 2012 09:02, inshu chauhan <insideshoes at gmail.com> wrote:
> I changed the programme to this :
> class Bag:
>     def __init__(self):
>
>         self.data = []
>
>     def add(self, x):
>         self.data.append(x)
>     def addtwice(self, x):
>          self.add(x)
>          self.add(x)
>          return x
> y = Bag()
> print y.addtwice(4)
>
> Now its not showing any error but result is same as the number passed for
> adding twice ....

That's because, although Bag.addtwice() is appending x to self.data a
couple of times, it isn't changing x - so

  return x

will just give back what you supplied as an argument. If you'd written

  return self.data

instead [or just done 'print y.data' after calling addtwice()], you'd
see that something has in fact happened to y.

By the way ... while Bag.addtwice() is legal Python [and I understand
that you're just playing around here], a method that both "does
something" [changes the object] and "gives something" [returns a
useful value] when that's not strictly necessary isn't brilliant
style.

Consider a couple of methods on built-in Python types:

>>> a = [4, 1, 3, 2]
>>> a.sort()                     # doesn't return anything useful, but ...
>>> a                            # ... changes 'a':
[1, 2, 3, 4]
>>> b = "one, two, three, four"
>>> b.title()                    # returns something useful ...
'One, Two, Three, Four'
>>> b                            # ... but doesn't change 'b':
'one, two, three, four'
>>>

A good rule for methods is "do one thing well". Sometimes doing that
one thing will necessarily mean both changing the object and returning
something - as in the pop() method on lists, for example - but where
possible, it's better to stick to one of "doing" or "giving".

 -[]z.



More information about the Python-list mailing list