我对这个有点生气,尝试使用 Python 3.3.0。
关于 http://docs.python.org/3/tutorial/classes.html有一个类示例,代码如下:
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
首先我想知道它是否缺少 Python3 通常需要的对象 class somename(object)。
class Bag(object):
其次,当我尝试运行它时,我收到此错误消息:
>>> 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'
什么鬼?
请您参考如下方法:
First I wonder that it is missing the object class somename(object) that Python3 normally demands.
在 Python 3 中,您的类将自动派生自 object,因此无需显式执行。 2 中没有这样做的唯一原因是为了向后兼容,因为所谓的新式(从对象派生)类的行为与旧式类略有不同。
a=Bag
这并没有生成 Bag 的实例,它只是表示 a 现在是 Bag 类的新名称。结果,当你使用
a.add('23')
您没有调用实例的 add 方法,因此实例没有作为第一个参数传递(不可能,因为还没有实例! ) 结果,它将“23”解释为 self 的值,因此您没有传递 x,因此
TypeError: add() missing 1 required positional argument: 'x'
尝试
>>> a = Bag()
>>> a.add('23')
>>> a.data
['23']
相反。
