Reputation: 411
I wonder if its possible to create a list (or something) of methods. For example, lets say I have a list
lst = []
And I want to have specific methods e.g. insert
, remove
and stuff. And I would like to call those, randomly from the list, so that I can add something like lst.add(3, 4)
but selecting the methods from the list of methods. Its silly, but its like I would like to do this: lst.listofmethods[3]
Possibly, the methods maybe should be stored in a dictionary instead?
Upvotes: 2
Views: 94
Reputation: 476584
Well there are two things that pop into mind:
dir(..)
returns you a list of the names of the methods. You can then use getattr(..)
to get the attribute that listens to the given name. For example:
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
So if you want to call append
(index 34), you could using:
getattr(lst,dir(lst)[34])('a')
You can construct a list of methods like:
listofmethods = [lst.append,lst.clear]
and then call it with:
listofmethod[1]()
to call clear()
on the list.
of course you can also define a dictionary that works almost equivalent:
dicofmethods = {'foo':lst.append,'bar':lst.clear}
and call with:
dicofmethods['foo'](42)
Upvotes: 3
Reputation: 1335
You can store functions into dictionary as well.
>>> def foo():
... print("foo")
...
>>> def bar():
... print("bar")
...
>>>
>>> foobar = {"foo": foo, "bar" : bar}
>>> foobar["foo"]()
foo
>>> foobar["bar"]()
bar
>>> foobar["bar"]
<function bar at 0x7f0561c6eae8>
>>>
Upvotes: 3
Reputation: 6990
Yes, you can store functions in a list, like this:
def f ():
print ('f')
def g ():
print ('g')
aList = [f, g]
for aFunction in aList:
aFunction ()
Upvotes: 2