python - 通过内置映射在 Python 中设置对象实例的属性

标签 python dictionary

必须有一种方法可以使用 map()

这个:

for inst in list_of_instances:
    inst.run()

可以这样做:

map(operator.methodcaller('run'), list_of_instances)

如何使用 map() 完成此操作?

for inst in list_of_instances:
    inst.some_setting = True

最佳答案

您可以使用 setattr :

map(lambda inst: setattr(inst, 'some_setting', True), list_of_instances)

或使用列表理解:

[setattr(inst, 'some_setting', True) for inst in list_of_instances]

顺便说一句,我认为简单的 for 循环比 map 更好,因为

  • for 循环更易于阅读。
  • map,列表理解版本生成临时列表([None, None, None, ..., None])

关于python - 通过内置映射在 Python 中设置对象实例的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19372175/

相关文章:

python - 如何将 salt 状态写入 pip 安装要求文件?

python - 如何在 Pyspark 中创建虚拟(0 字节)HDFS 文件

Python 循环 vs 理解列表 vs 映射的副作用(即不使用返回值)

python通过读取csv文件垂直而不是水平地做字典

python - 使用 Python 脚本按标本 ID 排序

python - 如何通过单击按钮重新执行我的 Python 程序

python - 如何将 scipy 与数组集成作为函数的一部分

c# - 在没有基础字典结构的 PowerShell 中使用 C# ExpandoObjects(动态)

c++ - const map & 作为函数参数

python - 检查一个词是否存在于字典中没有找到任何词