金志坚
金志坚

Reputation: 35

How can i build a list of Methods for iterative try in Python?

I have a Data strukture with differet levels like this: Data1--Methode1--Data2--Methode2--Data3 Data2=Data1.methode1

Each level of data need different method to approach. I am wondering if i can build a list of Methode to "dig in", for example [Method1,Method2,...]. And I will write one loop to "dig" the data by trying all the methods in the list.

I have this idea because we type string in screen when we call a method in python, for example I type print() to call print function. Can we make the string of a method replaceable, so i can change print() to list() or something else?

So can i build such a "Method list"? If I can, what data type sould I use?

Upvotes: 0

Views: 115

Answers (1)

lane
lane

Reputation: 886

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

Upvotes: 1

Related Questions