Re: classes

Discussion in 'Python' started by Zero Piraeus, Oct 24, 2012.

  1. Zero Piraeus

    Zero Piraeus Guest

    :

    On 24 October 2012 09:02, inshu chauhan <> 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.
    Zero Piraeus, Oct 24, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David

    Classes within classes

    David, Jul 21, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    4,924
    David
    Jul 22, 2005
  2. lonelyplanet999
    Replies:
    1
    Views:
    2,192
    VisionSet
    Nov 13, 2003
  3. Carfield Yim
    Replies:
    1
    Views:
    1,391
    Andrew Thompson
    May 31, 2004
  4. Razvan
    Replies:
    11
    Views:
    893
    Andrew Thompson
    Jul 17, 2004
  5. Razvan
    Replies:
    5
    Views:
    11,272
    Dale King
    Jul 27, 2004
Loading...

Share This Page