Reputation: 1806
I'm going slightly mad on this one, trying with Python 3.3.0 .
On http://docs.python.org/3/tutorial/classes.html there is a class example with the following code:
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
First I wonder that it is missing the object class somename(object) that Python3 normally demands.
class Bag(object):
Second, when I try to run it I get this error message:
>>> a=Bag
>>> a.add('23')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
a.add('23')
TypeError: add() missing 1 required positional argument: 'x'
WTF?
Upvotes: 1
Views: 1190
Reputation: 353329
First I wonder that it is missing the object class somename(object) that Python3 normally demands.
In Python 3, your class will automatically derive from object
, and so there's no need to do it explicitly. The only reason this wasn't done in 2 was for backward compatibility, because so-called new-style (deriving-from-object) classes behaved slightly differently from old-style classes.
a=Bag
This doesn't make an instance of Bag
, it just says that a
is now a new name for the Bag
class. As a result, when you use
a.add('23')
you're not calling the method add
of an instance, so the instance isn't being passed as the first argument (it can't be, as there isn't an instance yet!) As a result, it's interpreting '23' as your value for self
, and therefore you didn't pass an x
, hence
TypeError: add() missing 1 required positional argument: 'x'
Try
>>> a = Bag()
>>> a.add('23')
>>> a.data
['23']
instead.
Upvotes: 7