Python3 - Iterate over object methods with similar names

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()
...

Upvotes: 2

Views: 105

Answers (2)

Patrick Collins
Patrick Collins

Reputation: 10594

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

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

Or, abusing the list comprehension syntax a little:

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

Upvotes: 0

L3viathan
L3viathan

Reputation: 27323

All local object names are in locals():

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

Upvotes: 1

Related Questions