difference between locals() and globals() and dir() in python
假设此代码:
1 2 3 4 5 6 7 8 9 | >>> iterator=filter(lambda x: x % 3 == 0, [2, 18, 9, 22, 17, 24, 8, 12, 27]) >>> x=int() >>> locals() {'__package__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'iterator': <filter object at 0x02E732B0>, 'x': 0, '__doc__': None} >>> globals() {'__package__': None, '__spec__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'iterator': <filter object at 0x02E732B0>, 'x': 0, '__doc__': None} >>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'iterator', 'x'] >>> |
locals,globals和dir有什么区别? 用法是什么?
在全局范围内,
1 2 3 4 5 6 7 8 9 10 | >>> locals() == globals() #global scope, that is directly within the script (not inside a function. True >>> def a(): ... l = 1 ... print('locals() :',locals()) ... print('globals() :',globals()) ... >>> a() locals() : {'l': 1} globals() : {'BOTTOM': 'bottom', 'PROJECTING': 'proj.... |
从
globals()
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
从
locals()
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
为了回答有关用法的问题,一种用法是能够使用字符串来访问变量/名称。例如,如果您有一个名为
dir([object])
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
如果尝试在函数中执行它们,您会注意到
-
locals 返回一个在本地范围内声明的变量字典:https://docs.python.org/2/library/functions.html#locals -
globals 返回一个在全局范围内声明的变量字典:https://docs.python.org/2/library/functions.html#globals -
如果不提供参数,则
dir 的工作方式与locals 相似,但是如果将一个对象作为参数传递,则它将返回该对象的有效属性列表:https://docs.python .org等/ 2 /库/ functions.html#DIR
在模块级别运行以下三个命令时,它们具有相同的值:
1 2 3 4 5 6 | >>> sorted(locals().keys()) ['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc'] >>> sorted(dir()) ['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc'] >>> sorted(globals().keys()) ['A', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc'] |
如果进行这三个调用,则函数
1 2 3 4 5 6 7 8 9 | >>> def A(): ... print(sorted(locals().keys())) ... print(sorted(dir())) ... print(sorted(globals().keys())) >>> A() [] [] ['A', 'B', '__builtins__', '__doc__', '__name__', '__package__', 'a', 'loc'] |
您可以看到使用
但是dir()呢?
如果我们在上面的示例中使用函数
1 2 | >>> dir(A) ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] |
并获取功能对象
关于
在全局范围内(例如在交互式提示符下),您的
1 2 3 4 5 6 7 8 9 10 11 | x = 'some' y = 'this' def foo(x): y = 'that' print"My locals:", `locals()` print"My globals:", `globals()` # locals has x: other and y: that only # globals contains x: some, y: this and many more global names foo('other') |
值为'some'的全局变量
查看内建文档以获取详细信息,或查看Python范围规则的文档。
不带参数的