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

时间:2023-02-09 10:11:55

When a method is called on an object in python as:

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

obj.func()

then python passes the obj as the first argument to the func(). I want to do something like:

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

[obj1, obj2].func() 

and have it processed as:

并将其处理为:

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

Is there a way of defining this kind of methods in python?

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

2 个解决方案

#1


-2  

The only way to do exactly what you're asking for is to subclass python build-in class list.

完全按照你的要求做的唯一方法是继承python内置类列表。

This should help.

这应该有所帮助。

PS: it is a really bad thing to do that though.

PS:虽然这样做真的很糟糕。

#2


2  

If you use a list comprehension, you get basically what you need:

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

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

This is standard syntax and is easy to understand for other Python programmers.

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

#1


-2  

The only way to do exactly what you're asking for is to subclass python build-in class list.

完全按照你的要求做的唯一方法是继承python内置类列表。

This should help.

这应该有所帮助。

PS: it is a really bad thing to do that though.

PS:虽然这样做真的很糟糕。

#2


2  

If you use a list comprehension, you get basically what you need:

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

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

This is standard syntax and is easy to understand for other Python programmers.

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