被自我困惑[“名称”] = 文件名
我目前正在阅读这本精彩的书,名为“Dive into Python”。到目前为止,一切对我来说都有意义,但以下方法给我留下了一些疑问。它在关于初始化类的章节中:
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
这只是我不明白的最后一行。目前我所看到的方式是,调用对象有一个列表,其项目“名称”被分配了传递的参数的值。但这对我来说没有意义,因为我认为你只能通过整数访问列表索引。 书中关于这一行的内容如下:“您将参数文件名分配为该对象名称键的值。” name 键是每个对象定义的另一个变量(如 doc)吗?如果是的话,为什么可以这样访问?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
[...]
不仅仅适用于列表。任何类型都可以支持它,并且索引不一定必须是整数。self
是当前对象,根据您的代码,它派生自UserDict
,它支持 项目操作方法。[...]
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 fromUserDict
, which supports the item manipulation methods.您正在通过执行
class FileInfo(UserDict)
来扩展字典,这就是为什么您可以引用执行self['name'] = filename
的键You're extending a dictionary, by doing
class FileInfo(UserDict)
, that's why you can reference to the key doingself['name'] = filename
该类继承自
UserDict
我认为它是一个类似字典的类。对于 dict 的所有子类(保持 dict 接口完整),您可以将 self 视为 dict,这就是为什么您可以执行 self[key] = value 的原因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 treatself
as a dict, which is why you can doself[key] = value
不,
self
对象是UserDict
的子类,它是哈希表的一种形式(在 Python 中称为字典或dict
)。最后一行只是为文件名创建一个键“name”
。No, the
self
object is a subclass ofUserDict
, which is a form of hash table (known as a dictionary ordict
in Python). The last line is simply creating a key"name"
to the filename.由于您的类派生自 UserDict,因此它继承了
__getitem__()
方法采用任意键,而不仅仅是整数:Since your class derives from UserDict, it inherits a
__getitem__()
method that takes an arbitrary key, not just an integer: