Reputation: 1846
I have two functions doing different operations but I would like them to be called in another function randomly.
eg.
def func1(): do something
def funct2(): do something else
def func3(): select funct1() or funct2() randomly
Upvotes: 5
Views: 6461
Reputation: 34493
Collect the functions in a list and randomly choose one of them (using random.choice
) and call it!
>>> def f2():
return 2
>>> def f1():
return 1
>>> fns = [f1, f2]
>>> from random import choice
>>> choice(fns)()
1
>>> choice(fns)()
2
This is possible because Python functions are first class objects. Read up this link on first class objects in Python.
Upvotes: 15