繁体   English   中英

将变量从 class 传递到另一个 class python

[英]passing a variable from class to another class python

我有一个 python game.py 脚本,它使用名为 stage1、stage2、stage3 的 3 个文件运行 3 个阶段,并且它可以正常工作,但是在尝试从 stage2 到 stage3 中的 class 获取变量时向我的游戏添加新功能我似乎无法做到这一点。 stage1 生成一个 var(随机字符串名称),我将变量保存为 machine_id 这里是一个示例,

编辑 ## game.py 开始 3 个阶段如下

class Main:

    def run_stage1(self):
        start_stage1 = stage1.Stage1() 
        unique_machine_id = start_stage1.start()
        return unique_machine_id

    def run_stage2(self):
        start_stage2 = stage2.Stage2()  
        list_of_players = start_stage2.start()  
        return list_of_players
    
    def run_stage3(self, key, path):
        start_stage3 = stage3.Game(key, path)  
        start_stage3.game_start() 

主文件夹

 game.py

 sub_folder

子文件夹

stage1
stage2
stage3

            

下面的 stage2 为每个玩家创建一个唯一的 machine_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"""

这是我如何尝试将机器 id 从一个 class 传递到另一个但没有成功的示例。 我似乎无法理解其他教程

创建Stage3实例时,您需要将top作为初始化参数传递:

top = ...
stage3 = Stage3(top)

因此,您需要将其添加到 class 定义中:

class Stage3:
    def __init__(self, top):
        print(top.machine_id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM