Python 在名称依赖于另一个实例输入的实例/对象中运行方法';s法
我有一个Node类,它接受数量可变的关键字参数,这些参数表示玩家可以选择的选项以及应该连接到这些选项的目的地。因此,根据用户的输入,应该调用某个其他节点实例的play()方法Python 在名称依赖于另一个实例输入的实例/对象中运行方法';s法,python,class,methods,instance,Python,Class,Methods,Instance,我有一个Node类,它接受数量可变的关键字参数,这些参数表示玩家可以选择的选项以及应该连接到这些选项的目的地。因此,根据用户的输入,应该调用某个其他节点实例的play()方法 class Node: def __init__(self, txt, **kwargs): self.txt = txt self.__dict__.update(kwargs) c_key, d_key = "c", "d" choices = [
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()
类节点:
定义初始化(self,txt,**kwargs):
self.txt=txt
自我记录更新(kwargs)
c_key,d_key=“c”,“d”
选项=[val代表键,val代表自身。uuu dict_uuu.items()(如果c_代表键)
destinations=[val代表键,val代表自身。uu dict_uuu.items()(如果d_代表键)
自我选择
self.destinations=目的地
def播放(自我):
打印(self.txt)
尝试:
对于自我选择中的c:
印刷品(c)
除:
通过
决策=输入()
dec=int(决策)
对于自我选择中的选择:
如果选择。开始(决定):
self.destinations[dec-1].play()您的主代码可能应该更改为传递节点引用,而不是标识节点的字符串:
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
我知道解决办法可能很简单,但不是那么简单哈哈。太棒了,谢谢@亚洛,不客气。如果您认为答案解决了您的问题并有帮助,请接受并投票。