0

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!

2
  • I'm still not clear what you want to do. I think I am getting hung up on the fact that you have an infinite loop with only a print statement in it. Commented Jan 25, 2014 at 23:57
  • As I said its exaple code I just wanted to know how to run a function with user defined instanses. The loop is just there as an example of switching instances between functions. I hope this has cleared up your confusion :) Commented Jan 26, 2014 at 1:10

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.