classes

Chris Angelico rosuav at gmail.com
Wed Oct 24 09:48:36 EDT 2012


On Thu, Oct 25, 2012 at 12:02 AM, inshu chauhan <insideshoes at gmail.com> wrote:
> I changed the programme to this :
>     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 ....

Do you understand how function calls work? A function like
"y.addtwice" is called with an argument of 4, and the return value
from the function is the value of the expression.

some_value = y.addtwice(4)
print some_value

Take the return value and put it in the place where the function call
was. In this case, the return value is x, the number you passed in as
an argument.

What exactly do you expect addtwice to return? Should it return the
bag object (self)? Should it return True to say that it's been added
successfully (or False if there's an error)? Should it return the
number of items in the bag? Should it return 0 for success and a
nonzero error code for failure? Should it always return None, throwing
an exception if anything goes wrong? All of these make sense, you just
have to choose which one you want.

(I'm handwaving away a lot of complexity here, like un/bound methods
and member lookups. Bear with me. I'm also ignoring the fact that some
things just aren't Pythonic. The bear isn't complaining about that, so
nor should you.)

ChrisA



More information about the Python-list mailing list