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

如何通过外部函数创建示例类对象并在外部访问?Python3.6

Fixing the NameError When Accessing Objects Created in a Function

Hey there! Let’s break down what’s happening here and fix that NameError for you. The core issue is variable scope—objects created inside a function are local to that function by default. Once the function finishes running, those local variables get cleaned up, so you can’t access them from outside the function.

First, let’s look at a typical code snippet that would trigger this error, so we can see exactly where things go wrong:

class MyExampleClass:
    def __init__(self, label):
        self.label = label

def create_objects():
    # These are local variables limited to the function's scope
    obj_a = MyExampleClass("Object A")
    obj_b = MyExampleClass("Object B")

create_objects()
print(obj_a.label)  # Boom! NameError: name 'obj_a' is not defined

The cleanest, most Pythonic approach is to have your function return the objects you create. You can return them as a list, tuple, or dictionary to capture and use them outside the function.

Option 1a: Return as a Tuple/List

class MyExampleClass:
    def __init__(self, label):
        self.label = label

def create_objects():
    obj_a = MyExampleClass("Object A")
    obj_b = MyExampleClass("Object B")
    return obj_a, obj_b  # Return objects as a tuple

# Capture the returned objects in external variables
obj_a, obj_b = create_objects()

print(obj_a.label)  # Output: Object A
print(obj_b.label)  # Output: Object B

Option 1b: Return as a Dictionary (For Named Access)

If you have multiple objects and want to access them by name, a dictionary is ideal:

def create_objects():
    return {
        "user_profile": MyExampleClass("User Profile"),
        "system_settings": MyExampleClass("System Settings"),
        "app_logs": MyExampleClass("App Logs")
    }

object_store = create_objects()
print(object_store["user_profile"].label)  # Output: User Profile
print(object_store["app_logs"].label)      # Output: App Logs

You can declare the objects as global inside the function, which makes them accessible outside. However, this is generally discouraged because global variables can make code harder to debug and maintain. But here’s how it works if you absolutely need it:

def create_objects():
    global obj_a, obj_b  # Mark variables as global
    obj_a = MyExampleClass("Object A")
    obj_b = MyExampleClass("Object B")

create_objects()
print(obj_a.label)  # This works now, but use sparingly!

Solution 3: Use a Container Class (For Complex Scenarios)

If you’re managing a lot of objects, create a dedicated class to organize them. This keeps your code structured and avoids scope confusion:

class ObjectManager:
    def __init__(self):
        self.objects = {}
    
    def create_object(self, name, label):
        self.objects[name] = MyExampleClass(label)

# Usage
manager = ObjectManager()
manager.create_object("obj1", "First Object")
manager.create_object("obj2", "Second Object")

# Access objects through the manager
print(manager.objects["obj1"].label)  # Output: First Object

The first solution (returning objects in a container) is the best choice for most cases—it follows Python’s scope rules and keeps your code clean and maintainable.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:13:25