In python methods can be treated like variables.
Below is an example of two different method functions that contain no input arguments.
def method1():
# do something
return 1
def method2():
# do something else
return 2
methods = [method1, method2]
for m in methods:
print(m())
You need to be careful about arguments, it makes it easier if they all expect the same input. Below is another example where two methods are added to a list, they both expect a single integer as an argument.
def method1(arg):
# do something
return arg*1
def method2(arg):
# do something else
return arg*2
methods = [method1, method2]
for m in methods:
print(m(5))
Furthermore, we can consider the case where a method is trying something that may not work. For this we can add a try / except block to the loop. This will continue the loop if the method we are trying throws an exception.
def method0(arg):
return arg/(arg - 5)
def method1(arg):
# do something
return arg*1
def method2(arg):
# do something else
return arg*2
methods = [method0, method1, method2]
for m in methods:
try:
print(m(5))
except:
print(f'{m.__name__} did not work')
produces the output
method0 did not work
5
10
Lets say you have a class object with functions/methods inside. Those can be added to a list like this:
class DataType:
val = 5
def method0(self, arg):
return arg/(arg - self.val)
def method1(self, arg):
# do something
return arg*1
def method2(self, arg):
# do something else
return arg*2
# instantiate the class object
obj = DataType()
# add methods to list from the object
methods = [obj.method0, obj.method1, obj.method2]
for m in methods:
try:
print(m(5))
except:
print(f'{m.__name__} did not work')
Producing the same output as above
method0 did not work
5
10