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

如何实现Python模块范围内跨函数引用类实例?

Fixing the Name Error: Accessing Class Instances Across Functions

Got it, let's break down what's happening here. Your happy instance of the neato class is created inside the happyDance() function, which makes it a local variable—meaning it only exists within that function's scope. When main() tries to call print(happy.dance), happy isn't defined in main()'s scope, hence the NameError.

Here are a few solid ways to fix this and get that module-level access you want:

1. Return the Instance from happyDance() (Cleanest Approach)

Instead of creating the instance and letting it die in the function, return it so main() can capture and use it. This is the most Pythonic way because it keeps your code decoupled and avoids messy globals.

Modified code:

class neato: 
    def __init__(self): 
        self.dance = "I love to dance yadayaadadad!" 

def main(): 
    happy = happyDance()  # Capture the returned instance
    print(happy.dance) 

def happyDance(): 
    happy = neato() 
    return happy  # Return the instance to the caller

main() 

2. Use a Module-Level (Global) Variable

If you really need the instance to be accessible anywhere in the module, you can declare it as a global variable. Just be aware that overusing globals can make your code harder to debug and maintain—it's better to use this sparingly.

Modified code:

happy = None  # Module-level variable

class neato: 
    def __init__(self): 
        self.dance = "I love to dance yadayaadadad!" 

def main(): 
    happyDance() 
    print(happy.dance) 

def happyDance(): 
    global happy  # Declare we're using the global variable
    happy = neato() 

main() 

3. Encapsulate Everything in a Class (For Larger Codebases)

If your code is going to grow, wrapping functionality in a class keeps related code together and avoids scope issues entirely. This is great for organizing your logic:

Modified code:

class DanceManager:
    def __init__(self):
        self.happy = None

    class neato: 
        def __init__(self): 
            self.dance = "I love to dance yadayaadadad!" 

    def happyDance(self): 
        self.happy = self.neato() 

    def main(self): 
        self.happyDance() 
        print(self.happy.dance) 

# Run the code
dm = DanceManager()
dm.main()

Each of these approaches will solve your NameError, but the first one (returning the instance) is usually the best choice for simple cases—it keeps your code clean and follows best practices.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:09:49