我正在阅读Dive into python 2并且我在这个例子中遇到了麻烦:
class FileInfo(dict):
def __init__(self, filename = None):
self['name'] = filename
def __getitem__(self, key):
return self.data[key]
if __name__ == '__main__':
f = FileInfo('pixies.mp3')
print f.__getitem__('name')
我收到此错误:
Traceback (most recent call last):
File "FileInfo.py", line 12, in <module>
print f.__getitem__('name')
File "FileInfo.py", line 7, in __getitem__
return self.data[key]
AttributeError: 'FileInfo' object has no attribute 'data'
我正在使用 Python2.7
编辑 实际上,这段代码工作正常:
class FileInfo(dict):
def __init__(self, filename = None):
dict.__setitem__(self, 'name', filename)
def __getitem__(self, key):
return dict.__getitem__(self, key)
if __name__ == '__main__':
f = FileInfo('pixies.mp3')
print f.__getitem__('name')
但我想知道为什么另一个代码不起作用(Dive into Python 2 过时了吗?)