Search code examples
pythonclassmethodsinstance

Run a method in an instance/object whose name is dependent on an input from another instance's method


I have a Node class that takes a variable number of keyword arguments representing choices the player can take and destinations that should be connected to those choices. Thus depending on the input of the user a certain other Node instance's play() method should be called.

class Node:
def __init__(self, txt, **kwargs):
    self.txt = txt
    self.__dict__.update(kwargs)
    c_key, d_key = "c", "d"
    choices = [val for key, val in self.__dict__.items() if c_key in key]
    destinations = [val for key, val in self.__dict__.items() if d_key in key]
    self.choices = choices
    self.destinations = destinations
    
def play(self):
    print(self.txt)
    try:
        for c in self.choices:
            print(c)
    except:
        pass
    decision = input()
    dec = int(decision)
    for choice in self.choices:
        if choice.startswith(decision):
            self.destinations[dec-1].play() <- this obviously doesn't work


 node_0 = Node("Intro-Text", 
            c1 = "1) Choice A", 
            d1 = "node_1", 
            c2 = "2) Choice B",
            d2 = "node_2")

node_1 = Node("Text Node 1")

node_0.play()

When the user's input is "1" for example, node_1.play() should be called because d1 = "node_1", when the input is "2", node_2.play() because there is a 2 in d2 and so on.


Solution

  • Your main code should probably be altered to pass node references, rather than strings that identify the nodes:

    node_1 = Node("Text Node 1")
    node_2 = Node("Text Node 2")
    
    node_0 = Node("Intro-Text", 
                c1 = "1) Choice A", 
                d1 = node_1,         # pass node reference instead of string
                c2 = "2) Choice B",
                d2 = node_2)         # pass node reference instead of string