Python3 - 迭代具有相似名称的对象方法

时间:2022-04-15 10:18:50

I am trying to iterate a list of object methods with similar names. Is there any clever way I can do this. I have objects similar to this but would like to use an iterator instead of just making a list of functions.

我试图迭代一个具有相似名称的对象方法列表。我有什么聪明的方法可以做到这一点。我有类似于此的对象,但想使用迭代器而不是仅仅创建函数列表。

dog1.feed()
dog2.feed()
dog3.feed()
dog4.feed()
dog5.feed()
...

2 个解决方案

#1


All local object names are in locals():

所有本地对象名都在locals()中:

for i in range(1,6):
    locals()["dog" + str(i)].feed()

#2


Don't use string concatenation to do what's basically an eval. Just put your dogs in a list:

不要使用字符串连接来执行基本上是eval的操作。把你的狗放在一个清单中:

for dog in [dog1, dog2,...,dogn]:
  dog.feed()

Or, abusing the list comprehension syntax a little:

或者,滥用列表理解语法一点:

[dog.feed() for dog in [dog1, dog2,...,dogn]

#1


All local object names are in locals():

所有本地对象名都在locals()中:

for i in range(1,6):
    locals()["dog" + str(i)].feed()

#2


Don't use string concatenation to do what's basically an eval. Just put your dogs in a list:

不要使用字符串连接来执行基本上是eval的操作。把你的狗放在一个清单中:

for dog in [dog1, dog2,...,dogn]:
  dog.feed()

Or, abusing the list comprehension syntax a little:

或者,滥用列表理解语法一点:

[dog.feed() for dog in [dog1, dog2,...,dogn]