【问题标题】:Run a method in an instance/object whose name is dependent on an input from another instance's method在名称依赖于另一个实例方法的输入的实例/对象中运行方法
【发布时间】:2026-01-15 22:10:01
【问题描述】:

我有一个 Node 类,它接受可变数量的关键字参数,代表玩家可以采取的选择以及应该连接到这些选择的目的地。因此,根据用户的输入,应该调用某个其他 Node 实例的 play() 方法。

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()

例如当用户输入为“1”时,应该调用node_1.play(),因为d1 =“node_1”,当输入为“2”时,node_2.play()因为d2中有一个2,并且以此类推。

【问题讨论】:

    标签: python class methods instance


    【解决方案1】:

    您的主代码可能应该被更改为传递节点引用,而不是标识节点的字符串:

    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
    

    【讨论】:

    • 我知道解决方案可能很简单,但没那么简单哈哈。太棒了,谢谢!
    • @yalo,不客气。如果您认为答案解决了您的问题并有所帮助,请接受并投票赞成。