Reputation: 51
How can I create a list of methods in python to be applied to an object?
Given some arbitrary class:
class someClass:
def __init__(self, s):
self.size = s
def shrink(self):
self.size -= 1
def grow(self):
self.size += 1
def invert(self):
self.size = -self.size
I want to be able to write an iterable object like this list:
instructions = [shrink, grow, shrink, shrink, grow, invert]
To be run through a for-loop later:
elephant = someClass(90)
sizeList = []
for ins in instructions:
elephant.ins()
sizeList.append(elephant.size)
I've done something similar with functions before. Not being able to do this with methods would require me to rewrite an intimidating amount of code...
Upvotes: 1
Views: 1392
Reputation: 114098
You could create a list of the method names then use getattr()
to access the methods:
instructions = ["shrink", "grow", "shrink"]
for i in instructions:
getattr(elephant, i)()
Upvotes: 6
Reputation: 288280
You can use dir
to get all property names of an object, and getattr
to get a property value of an object. You may also want to not call any non-callable properties (such as 2
or "foo"
):
for m in dir(elephant):
if not m.startswith('_'):
f = getattr(elephant, m)
if callable(f): # Do not try to call non-function properties
f()
Upvotes: 0
Reputation: 208695
As an alternative to using strings for your list of instructions, you could do the following:
instructions = [someClass.shrink, someClass.grow, someClass.shrink,
someClass.shrink, someClass.grow, someClass.invert]
elephant = someClass(90)
sizeList = []
for ins in instructions:
ins(elephant)
sizeList.append(elephant.size)
Upvotes: 3
Reputation: 77167
Possibly naïvely:
for ins in instructions:
getattr(elephant, ins)()
Gotchas include that ins
must be a string and that it's probably wise to validate both that ins
is what you really want to call and that getattr(elephant, ins)
is a callable.
Upvotes: 0