I’m having some trouble in python with classes and objects. I have two classes, and I instantiated an object of each. I’d like to pass those objects into a function when the user types a certain string. The function would then call a class method of the object it takes. (The methods have the same name for each class). I made an example file below:
class Test1(object):
def method1(self):
print("test1")
class Test2(object):
def method1(self):
print("test2")
def Call(something):
return something.method1
def Call2(something):
y = input("> ")
return something.method1
array = [Test1(), Test2()]
my_dict = {'call': Call(array[0]), 'call2': Call2(array[1])}
x = input("> ")
if x in my_dict:
my_dict[x]()
What I think happens is Call2() gets called at runtime and ask for input. Then the second input() gets called. Could someone explain why Call2() runs even when the if statement doesn’t get a chance to evaluate a string? There is probably a lot of things I’m misunderstanding. Any help is appreciated.
EDIT: Okay, I understand that the functions are called during the declaration of the dict. How would you go about linking a function to the dict while still passing the object to it?
When you run this, it will get to this line:
That will call
CallandCall2– this is where the firstinputis being called (you can see this if you change yourinputprompts to something different for each one, so you can tell which one is being called (i.e. rather than"> ").Does that clarify things, or is it something different you’re not understanding?