Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32050 > unrolled thread

Re: classes

Started byZero Piraeus <schesis@gmail.com>
First post2012-10-24 11:14 -0400
Last post2012-10-24 11:14 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: classes Zero Piraeus <schesis@gmail.com> - 2012-10-24 11:14 -0400

#32050 — Re: classes

FromZero Piraeus <schesis@gmail.com>
Date2012-10-24 11:14 -0400
SubjectRe: classes
Message-ID<mailman.2779.1351091690.27098.python-list@python.org>
:

On 24 October 2012 09:02, inshu chauhan <insideshoes@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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web