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

Python中locals()函数为何输出全局变量?末尾locals含全局y的疑问

Understanding locals() and globals() in Your Class Definition

Let's start by looking at your code again, formatted for clarity:

y=3
class A:
    x = 1
    print(locals())
    print()
    print(globals())
    print()
    print(locals())

Now let's break down your two questions one by one, like we're chatting through a tricky Python quirk.

1. Why does locals() seem to output global variables?

First, let's clear up a common misconception: in the top-level of a class definition, locals() does NOT return the global namespace—it returns a temporary dictionary Python uses to build the class's attributes.

You might be confused because this temporary dict includes auto-generated entries like __module__ (which holds the name of the module where the class lives, e.g., __main__). These are special attributes Python adds automatically, not the global variables you defined (like y=3).

To get straight on the core difference between the two functions:

  • globals() always returns the module-level global namespace, which includes all your global variables, built-in functions, and module-level attributes.
  • locals() is context-dependent:
    • At the module level (outside any class/function), locals() is identical to globals().
    • Inside a function, it returns the function's local namespace.
    • Inside a class definition's top-level code, it returns the temporary namespace that will become the class's __dict__ (the dictionary storing class attributes like x).

So if you’re seeing entries that look "global" in locals(), they’re likely those auto-added special attributes, not your user-defined global variables.

2. Why does the last locals() include the global variable y?

Wait a second—under normal circumstances, it shouldn’t! When you run your code as-is, the final locals() call should return the same temporary class namespace as the first one: {'__module__': '__main__', '__qualname__': 'A', 'x': 1}.

If you are seeing y in that final locals() output, here are a few possible reasons:

  • You might have accidentally assigned y somewhere in the class body (even something as simple as y = y would add y to the class’s temporary namespace).
  • If you’re running this in an interactive Python shell, there could be leftover state from previous commands messing with the namespace. Try running the code as a standalone script instead to avoid this.
  • It’s possible you mixed up the globals() and locals() outputs—globals() does include y, so double-check which block you’re looking at.

Double-check your code and the actual output—unless you explicitly add y to the class’s namespace, locals() in the class definition won’t include it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 11:58:14