Skip to main content
 首页 » 编程设计

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

2025年05月04日16leader

必须有一种方法可以使用 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])