classes

Dave Angel d at davea.name
Wed Oct 24 08:55:28 EDT 2012


On 10/24/2012 08:11 AM, inshu chauhan wrote:
> I was just trying out a programme for learning classes in python
>
> The prog below is showing an error which it should not show :
>
> class Bag:
>     def __init__(self, x):
>         self.data = []
>
>     def add(self, x):
>         self.data.append(x)
>     def addtwice(self, x):
>          self.add(x)
>          self.add(x)
> y = Bag(4)
> print " Adding twice of %4.2f gives " % (y.addtwice())
>
Perhaps you're confusing the two x parameters.  They are totally
independent local variables, and the value of one is not in any way
"remembered" for the other.  When you want to save things between
multiple methods of an object, then store them in the object, perhaps in
self.data  As it stands, the __init__ does not save the x at all, so the
4 that's passed into the initializer is thrown away.

You call addtwice(), but don't supply any value to add.  y serves as the
self value, but you have no x value.  What value did you intend to add?

You'll have another problem, in that addtwice() doesn't return any value
(so it returns None).  Therefore the print isn't going to work.  Please
separate the print from the calculations, and the problems will be lots
easier to figure out.  The wording of the string implies it's going to
display two values, but the only value given it is None.

> Error is :
>
> Traceback (most recent call last):
>   File "Z:\learning Python\learn5.py", line 35, in <module>
>     print " Adding twice of %4.2f gives " % (y.addtwice())
> TypeError: addtwice() takes exactly 2 arguments (1 given)
>
> why the prog is having this error with self nd x as arguments ???
>
>
self and x are parameters.  You don't pass an argument for x to be bound to.




-- 

DaveA




More information about the Python-list mailing list