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

时间:2021-05-25 14:53:21

标签: python class variables

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

Edited ## the 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"""

这是一个示例,说明我如何尝试将 Machine id 从一个类传递到另一个类,但没有成功。我似乎无法理解其他教程

1 个答案:

答案 0 :(得分:0)

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

top = ...
stage3 = Stage3(top)

因此您需要将其添加到您的类定义中:

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