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

Python中如何使用其他函数的局部变量?解决‘results非全局变量’报错

Hey there! Let's tackle your two Python questions one by one—they both tie into variable scope, which is a super common pitfall when you're getting the hang of functions in Python.

1. How to access a local variable from another function in Python?

First off, remember: local variables are only accessible inside the function they're defined in by default. That's Python's way of keeping your code organized and preventing accidental side effects. But if you need to share that variable, here are the best ways to do it:

  • Return the variable (most recommended)
    The cleanest approach is to have the function return the local variable, then capture that return value wherever you need it. For example:

    def generate_data():
        local_result = "I'm from generate_data!"
        return local_result
    
    # Use the variable in another part of your code
    fetched_data = generate_data()
    print(fetched_data)  # Output: I'm from generate_data!
    

    This follows Python's design principles and keeps data flow explicit.

  • Use global variables (only if absolutely necessary)
    You can declare a variable as global so all functions can access it, but be warned—this can make your code hard to debug and messy as it grows. Here's how it works:

    shared_var = None
    
    def set_var():
        global shared_var
        shared_var = "Now I'm global"
    
    def get_var():
        print(shared_var)
    
    set_var()
    get_var()  # Output: Now I'm global
    
  • Wrap variables in a class (for structured state sharing)
    If you have multiple related variables to share across functions, using a class is a much cleaner approach. Instance attributes are accessible across all methods of the class:

    class DataHandler:
        def __init__(self):
            self.results = []
    
        def add_result(self):
            self.results.append("New entry")
    
        def show_results(self):
            print(self.results)
    
    handler = DataHandler()
    handler.add_result()
    handler.show_results()  # Output: ['New entry']
    
2. Fixing the "results is not a global variable" error & appending res from foo2() to results

Let's start with why you're seeing that error: If you're trying to modify results inside foo2(), Python either thinks results is a local variable (and you haven't defined it yet) or you tried to reference it as global without properly declaring it. Here are the solutions based on your scenario:

Scenario 1: results is a global variable

If results lives in the global scope, you need to explicitly tell Python you're using the global version inside foo2() with the global keyword:

results = []  # Global list

def foo2():
    res = "Value to append"
    global results  # Declare we're using the global results
    results.append(res)

foo2()
print(results)  # Output: ['Value to append']

Without global, Python would try to create a new local variable named results inside foo2(), which causes the error when you try to append to it.

Scenario 2: results is a local variable in another function

Instead of trying to access another function's local variable directly (which is bad practice), pass results as an argument to foo2(). Since lists are mutable, modifying the list inside foo2() will affect the original list:

def main_function():
    results = []
    # Pass results to foo2 so it can append to it
    foo2(results)
    return results

def foo2(target_list):
    res = "Appended from foo2"
    target_list.append(res)

final_results = main_function()
print(final_results)  # Output: ['Appended from foo2']

This is way better than using globals because it's clear where the data is coming from and going to.

Scenario 3: Using nested functions (closures)

If foo2() is nested inside another function, you can use a closure to access the outer function's local variable:

def outer_function():
    results = []

    def foo2():
        res = "Closure magic!"
        results.append(res)

    foo2()
    return results

print(outer_function())  # Output: ['Closure magic!']

Nested functions can access variables from their enclosing scope, which is handy for keeping related logic together.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:30:50