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

如何更新跨模块全局变量?Python变量更新失效求助

问题原因

Python中像int这类不可变类型,传递给函数时是传对象引用的副本。你在module_doors.one()里执行batteries = 1这类赋值操作时,只是在函数内部创建了一个全新的int对象,和外部传入的变量没有关联,所以外部变量的初始值不会被更新。

解决方案

以下是几种可行的解决办法,可根据你的代码规模选择:

方法1:返回修改后的变量值

修改module_doors中的函数,让它返回更新后的变量值,在调用处接收并覆盖原变量。

修改后的module_doors代码:

def one(pills, batteries, lighter):
    while True:
        doorone = input("A, B or C?:\n").lower()
        if doorone not in ('a', 'b', 'c'):
            print("That item doesn't exist, try again.\n")
        else:
            break
    if doorone == 'a':
        batteries = 1
        print('These could come in handy later.')
    elif doorone == 'b':
        lighter = 1
        print("Maybe it's a light source. Doesn't look brand new though, not sure how long it'll last.")
    elif doorone == 'c':
        pills = 1
        print('Could save your life, good choice.')
    # 返回更新后的三个变量
    return pills, batteries, lighter

调用处代码修改:

import module_doors
import time
import module_spacing

def lobby(pills, batteries, lighter):
    # 假设lobbydeci已提前定义
    if lobbydeci.lower() == 'b':
        print("")
        time.sleep(0.3)
        print('Only one key remaining, Nice!')
        print('')
        print("It says '0001' on the tag.")
        module_spacing.spacing()
        # 接收返回值,覆盖原变量
        pills, batteries, lighter = module_doors.one(pills, batteries, lighter)
        # 若two()也需修改变量,同样处理返回值
        pills, batteries, lighter = module_doors.two(pills, batteries, lighter)
        print(batteries)
        print(lighter)
        print(pills)

方法2:用可变容器封装变量

把变量放进字典(或列表)这类可变容器中,函数内修改容器的内容会直接影响外部的容器对象。

修改后的module_doors代码:

def one(items):
    while True:
        doorone = input("A, B or C?:\n").lower()
        if doorone not in ('a', 'b', 'c'):
            print("That item doesn't exist, try again.\n")
        else:
            break
    if doorone == 'a':
        items['batteries'] = 1
        print('These could come in handy later.')
    elif doorone == 'b':
        items['lighter'] = 1
        print("Maybe it's a light source. Doesn't look brand new though, not sure how long it'll last.")
    elif doorone == 'c':
        items['pills'] = 1
        print('Could save your life, good choice.')

调用处代码修改:

import module_doors
import time
import module_spacing

def lobby():
    # 用字典存储所有物品状态
    items = {'pills': 0, 'batteries': 0, 'lighter': 0}
    if lobbydeci.lower() == 'b':
        print("")
        time.sleep(0.3)
        print('Only one key remaining, Nice!')
        print('')
        print("It says '0001' on the tag.")
        module_spacing.spacing()
        module_doors.one(items)
        module_doors.two(items)
        print(items['batteries'])
        print(items['lighter'])
        print(items['pills'])

方法3:用类管理状态(适合复杂场景)

如果你的项目有大量状态需要维护,用类封装变量和操作会更清晰易维护。

示例代码(module_doors.py):

class PlayerItems:
    def __init__(self):
        self.pills = 0
        self.batteries = 0
        self.lighter = 0

    def door_one(self):
        while True:
            doorone = input("A, B or C?:\n").lower()
            if doorone not in ('a', 'b', 'c'):
                print("That item doesn't exist, try again.\n")
            else:
                break
        if doorone == 'a':
            self.batteries = 1
            print('These could come in handy later.')
        elif doorone == 'b':
            self.lighter = 1
            print("Maybe it's a light source. Doesn't look brand new though, not sure how long it'll last.")
        elif doorone == 'c':
            self.pills = 1
            print('Could save your life, good choice.')

    def door_two(self):
        # 实现door two的逻辑,直接修改self的属性即可
        pass

调用处代码:

import module_doors
import time
import module_spacing

def lobby():
    player_items = module_doors.PlayerItems()
    if lobbydeci.lower() == 'b':
        print("")
        time.sleep(0.3)
        print('Only one key remaining, Nice!')
        print('')
        print("It says '0001' on the tag.")
        module_spacing.spacing()
        player_items.door_one()
        player_items.door_two()
        print(player_items.batteries)
        print(player_items.lighter)
        print(player_items.pills)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:30:41