在名称依赖于另一个实例的输入的实例/对象中运行方法's方法



我有一个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()

当用户的输入是"0"时;1〃;例如,应该调用node_1.play((,因为d1=";node_ 1";,当输入是"0"时;2〃;,node_2.play((,因为d2中有一个2,依此类推。

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

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

最新更新