Python中locals()和globals()有何区别?

2026-05-24 13:380阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计381个文字,预计阅读时间需要2分钟。

Python中locals()和globals()有何区别?

Python 的 `locals()` 和 `globals()` 是内置函数,它们提供了访问局部和全局变量的方式。`locals()` 返回当前作用域内的局部变量字典,而 `globals()` 返回当前全局作用域的变量字典。

示例代码如下:

pythondef test(arg): a=1 b=2 data_dict={} print(locals()) print(globals())if __name__=='__main__': test(1)

1、locals() 和 globals() 是python 的内建函数,他们提供了字典的形式访问局部变量和全局变量的方式。

阅读全文

本文共计381个文字,预计阅读时间需要2分钟。

Python中locals()和globals()有何区别?

Python 的 `locals()` 和 `globals()` 是内置函数,它们提供了访问局部和全局变量的方式。`locals()` 返回当前作用域内的局部变量字典,而 `globals()` 返回当前全局作用域的变量字典。

示例代码如下:

pythondef test(arg): a=1 b=2 data_dict={} print(locals()) print(globals())if __name__=='__main__': test(1)

1、locals() 和 globals() 是python 的内建函数,他们提供了字典的形式访问局部变量和全局变量的方式。

阅读全文