Confused by self["name"] = filename
I'm currently reading this amazing book called "Dive into Python". Up to now everything has made sense to me, but the following method has left me with some questions. Its in the chapter about initializing classes:
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
It's only the last line I don't get. The way 开发者_开发知识库I see it at the moment, the calling object has a list, whose item "name" is assigned the value of the argument passed. But this doesn't make sense to me, since I thought that you can only access list indices by integers. The book says the following about this line: "You're assigning the argument filename as the value of this object's name key." Is the name key another variable that every object defines (like doc)? And if yes, why can it be accessed like that?
[...]
isn't just for lists. Any type can support it, and the index doesn't necessarily have to be an integer. self
is the current object, which according to your code derives from UserDict
, which supports the item manipulation methods.
You're extending a dictionary, by doing class FileInfo(UserDict)
, that's why you can reference to the key doing self['name'] = filename
The class inherits from UserDict
which I presume is a dict-like class. For all subclasses of dicts (which keeps the dict interface intact), you can treat self
as a dict, which is why you can do self[key] = value
No, the self
object is a subclass of UserDict
, which is a form of hash table (known as a dictionary or dict
in Python). The last line is simply creating a key "name"
to the filename.
Since your class derives from UserDict, it inherits a __getitem__()
method that takes an arbitrary key, not just an integer:
self["name"] = filename # Associate the filename with the "name" key.
精彩评论