You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python脚本之间共享变量?附实操案例咨询

跨脚本共享username变量的实现方案

针对你的需求,有几种简单直接的实现方式:

方法1:让函数返回用户名

这是最直观的方式,修改Intro.py中的函数使其返回获取到的用户名,再在Main.py中接收该返回值。

修改后的Intro.py:

def Intro():
    print("Welcome to *game name here*!")
    username = input("What is your username?")
    return username

Main.py:

import Intro
username = Intro.Intro()
print(username)

方法2:使用模块级变量

将username定义为Intro模块的全局变量,在函数内部修改它,之后在Main.py中直接通过模块名访问该变量。

修改后的Intro.py:

# 定义模块级变量
username = ""

def Intro():
    # 声明使用全局变量
    global username
    print("Welcome to *game name here*!")
    username = input("What is your username?")

Main.py:

import Intro
Intro.Intro()
# 通过模块名访问变量
print(Intro.username)

方法3:用类封装(适合复杂场景)

如果后续游戏逻辑会更复杂,用类封装相关状态和行为会更便于扩展维护。

修改后的Intro.py:

class GameIntro:
    def __init__(self):
        self.username = ""
    
    def collect_username(self):
        print("Welcome to *game name here*!")
        self.username = input("What is your username?")

Main.py:

from Intro import GameIntro
intro = GameIntro()
intro.collect_username()
print(intro.username)

这些方法里,方法1最适配你的当前需求,简单直接;如果后续需要在多个函数中共享该用户名,方法2或3会更灵活。

内容的提问来源于stack exchange,提问作者Hungry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:52:42