python - 用[ ]设置对象变量时叫什么?

标签 python

如果我有一个 dict 对象说 values = {'a': 'alpha', 'b': 'bravo'}

我见过一些用例,其中可以执行 values['a'] 来获取 a 键的值。

现在我知道这是访问 dict 值的正常方式,但我也看到它与对象一起使用,例如 Tk.Scrollbar['command'] = yadayada.

这种将 [ ] 与对象一起使用的做法是否有名称或文档?

最佳答案

[ ] 称为索引或切片(有时也称为类似数组/序列/映射的访问)。 x[idx] = val 称为索引或切片赋值

负责实例在索引或切片时如何操作的方法是:

  • __getitem__ ,
  • __setitem__
  • __delitem__ .
  • (在 Python-2.x 中还有 __getslice__,...但是自 python 2.0 以来这些已被弃用 - 如果您不从使用这些的类继承,则您不需要那些)

例如(缺少任何实际实现,只有一些 print):

class Something(object):
    def __getitem__(self, item):
        print('in getitem')
    def __setitem__(self, item, newvalue):
        print('in setitem')
    def __delitem__(self, item):
        print('in delitem')

例如:

>>> sth = Something()
>>> sth[10]  
in getitem
>>> sth[10] = 100  
in setitem
>>> del sth[10]  
in delitem

关于python - 用[ ]设置对象变量时叫什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44080311/

相关文章:

python - 在 os x-Mountain Lion 上安装 p4python 时出错

python - 如何测试(使用 unittest)Django View 的 HTML 输出?

python - 将颜色条添加到现有轴

Python 子进程 readline() 挂起;不能使用普通选项

python - 带有 Python "Table has X columns but Y were supplied"的 SQLite

python - 创建一个新的字典值列表,其键与单独列表中的项目匹配

python - 尝试编写函数来递归计算单词在Python中文本文件中出现的次数

python - 如何从 Python 3 中的 tkinter 文件对话框获取字符串?

python - Pipenv 全局环境

python - 密码字段不通过 Python 使用 Selenium 获取 key