Python 可以在对象列表上调用的方法

Python method that can be called on a list of objects

当在 python 中的对象上调用方法时:

obj.func()

然后 python 将 obj 作为第一个参数传递给 func()。我想做类似的事情:

[obj1, obj2].func() 

并将其处理为:

[obj1.func(), obj.func()]

在python中有没有办法定义这种方法?

如果你使用列表理解,你基本上会得到你需要的:

[obj.func() for obj in [obj1, obj2]]

这是标准语法,其他 Python 程序员很容易理解。

完全按照您的要求进行操作的唯一方法是 subclass python 内置 class list.

This 应该有帮助。

PS: 不过这样做真的很糟糕。