【发布时间】: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