Daniel K
Daniel K

Reputation: 13

How do I loop dict and use the value as functions of an object?

I have a dictionary of values and initialize an object. The dictionary values contains all the modules of the object, so how can I achieve something like this?

test_action = {
    '1': 'addition',
    '2': 'subtraction'
}

class test:
    def __init__(self, a,b,c):
        self.a = a
        self.b = b
        self.c = c

    def addition(self):
        return self.a + self.b + self.c

    def subtraction(self):
        return self.a - self.b - self.c


def main():
    xxx = test(10,5,1)
    for key,action in test_action.items():
        print(xxx.action())

Upvotes: 1

Views: 37

Answers (2)

Amitkumar Karnik
Amitkumar Karnik

Reputation: 931

def main():
    xxx = test(10,5,1)
    for key,action in test_action.items():
        if hasattr(xxx, action):
            print "perforning: {}".format(action)
            print xxx.__getattribute__(action)()

#op
perforning: addition
16
perforning: subtraction
4

Upvotes: 0

blhsing
blhsing

Reputation: 107015

You should refer to the functions as objects rather than strings, so that:

class test:
    def __init__(self, a,b,c):
        self.a = a
        self.b = b
        self.c = c

    def addition(self):
        return self.a + self.b + self.c

    def subtraction(self):
        return self.a - self.b - self.c

test_action = {
    '1': test.addition,
    '2': test.subtraction
}

xxx = test(10,5,1)
for key, action in test_action.items():
    print(key, action(xxx))

would output:

1 16
2 4

Upvotes: 0

Related Questions