user3157264
user3157264

Reputation: 119

Execute a function with an instance based on user input (in conjunction with a class) [Python]

While I was working on a little project I hit a bit of a snag. I want to execute a function with certain instance of a class but the user needs to input them. I know you can just input the instance in the code itself like:

run(instance1,instance2)

A small example in psuedo code. ( I know the code is pointless its just to illustrate the point.)

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

test1 = main(10, 443, 5, 46)
test2 = main(340, 3, 554, 2134)
test3 = main(140, 3, 98, 6)
test4 = main(0, 345, 7, 46)

def check(instance_a, insance_b):
    print instance_a.b, instance_b.c

def run(instance_a, instance_b):
    while True:
       check(instance_a, instance_b)

instance_a = raw_input('set instance a')
instance_b = raw_input('set instance b')

run(instance_a, instance_b)

The idea is that the user can input test1,test2,test3,test4 and the programm would then execute all of the functions with the 2 isntances chosen. Is this at all possible? Or do you have to manually make all the options with if statements? Many thanks in advance!

Upvotes: 0

Views: 119

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122067

To do this, store the instances in a dictionary by name, rather than as separate variable names:

tests = {'test1': main(...), 'test2': main(...), ...}

Then you can easily access them based on the user input:

instance_a = raw_input('set instance a')
instance_b = raw_input('set instance b')
run(tests[instance_a], tests[instance_b])

and add some simple checking for valid input:

if instance_a not in tests:
    # complain to user

Upvotes: 1

Related Questions