Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #32050
| References | <CAFqGZRE1LbAgoOCAKuynYBw4Rj6++p+misZrsXmv1nwivHuNwg@mail.gmail.com> <5087E540.8060504@davea.name> <CAFqGZRFxfe=_N+1mhSD7ObedHgy6j9vKUhMgbU0smfOEC-wEyg@mail.gmail.com> |
|---|---|
| From | Zero Piraeus <schesis@gmail.com> |
| Date | 2012-10-24 11:14 -0400 |
| Subject | Re: classes |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2779.1351091690.27098.python-list@python.org> (permalink) |
: 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.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: classes Zero Piraeus <schesis@gmail.com> - 2012-10-24 11:14 -0400
csiph-web