Python 将变量从类传递到另一个类
我有一个python game.py脚本,它使用名为stage1、stage2、stage3的3个文件运行3个阶段,它可以正常工作,但是在我的游戏中添加新功能时,当试图从stage2到stage3中的类中获取变量时,我似乎无法正确获得它。stage1生成一个var(随机字符串名),我将变量保存为machine_id,这里是一个示例 编辑的35;#game.py开始以下3个阶段 主文件夹Python 将变量从类传递到另一个类,python,class,variables,Python,Class,Variables,我有一个python game.py脚本,它使用名为stage1、stage2、stage3的3个文件运行3个阶段,它可以正常工作,但是在我的游戏中添加新功能时,当试图从stage2到stage3中的类中获取变量时,我似乎无法正确获得它。stage1生成一个var(随机字符串名),我将变量保存为machine_id,这里是一个示例 编辑的35;#game.py开始以下3个阶段 主文件夹 game.py sub_folder 子文件夹 stage1 stage2 stage3
game.py
sub_folder
子文件夹
stage1
stage2
stage3
下面的阶段2为每个玩家创建一个唯一的机器id
#This is stage2
def start_gui(machine_id):
root1 = tk.Tk()
top = Toplevel1(root1, machine_id)
root1.mainloop()
class Toplevel1:
def __init__(self, top=None, machine_id="TEST MACHINE ID"):
self.machine_id = machine_id
"""other code and functions below, and passing machine_id within same class i can do"""
if __name__ == '__main__':
start_gui("555f9f3b573f4c41e7de2c5b3f97ed54") #Takes Machine ID As Argument
我要做的是将机器id传递给stage3
下文第3阶段
#This is stage3
from sub_folder import stage2 #<- imported stage2
class Stage3:
def __init__(self):
fetch_var_machine_id = stage2.Toplevel1(self, machine_id) # << This is what i am using but it does not pass the variable.
print(fetch_var_machine_id) # <This Just Returns 'S' Not the machine_id
def start(self, fetch_var_machine_id):
"""Do stuff"""
return """Do Stuff"""
#这是第3阶段
从子文件夹导入stage2#创建Stage3
实例时,需要将top
作为初始化参数传递:
top = ...
stage3 = Stage3(top)
因此,您需要将其添加到类定义中:
class Stage3:
def __init__(self, top):
print(top.machine_id)
Stage3
在哪里实例化?按照上面编辑的内容,从主game.py文件编辑question.py。调用tkinter top似乎没有必要。在调用run_stage1
之后,您如何处理结果?您需要将其传递到Stage3
(您似乎已将其重命名为Game
)。请参见和如何创建一个。请阅读。谢谢您的回复,但是我无法让它发挥作用。我更不明白。顶部=。。。stage3=stage3(顶部)我的意思是,..
代码与上面示例中的代码相同,然后在其下方添加stage3
行。请回答我提出的关于在何处实例化stage3
的问题。请编辑您的问题。我已编辑了问题。谢谢
class Stage3:
def __init__(self, top):
print(top.machine_id)