遇到场景根据一些业务生成参数,但是实在不想一个一个的写,然后就搜索了一下,果然有这么个函数可以,就是locals(),话不多说,看示例,记录下:
源码:
def locals(*args, **kwargs): # real signature unknown
"""
Return a dictionary containing the current scope's local variables.
NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
"""
pass
—说实话这个源码没看懂,发现看源码遇到很多这种啥都没有就是实现了函数的功能,后来查询了下看到一个解释如下:
PyCharm在骗你,您正在查看的源代码是PyCharm创建的伪造品。 PyCharm知道哪些函数或object 应该在那里,它可以使用函数docstrings来猜测它们的签名,但是它不知道函数体应该是什么样的。python (特值cpython)是用c 语言写的。如果您想查看真实的源代码,可以在https://github.com/python/cpython/blob/master/Objects/dictobject.c
作者:黄哥
链接:https://www.zhihu.com/question/264328313/answer/279561981
来源:知乎
```‘
鉴于我的C语言忘记的差不多了~,等弄明白了再回来添加,现在先看该函数的功能实现。
def a():
a1=1
a2=“hello”
a3=[1,2,3]
a4={“a”:1,“a2”:“a2”}
print(locals())
b=3
c=“你好呀!”
print(locals())
a()
运行结果:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000235221C1910>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'F:/python/WEBAuto_pythonV3_20200619/testTmp/tmp.py', '__cached__': None, 'a': <function a at 0x00000235221A51F0>, 'b': 3, 'c': '你好呀!'}
{'a1': 1, 'a2': 'hello', 'a3': [1, 2, 3], 'a4': {'a': 1, 'a2': 'a2'}}
是不是一目了然啊,等我研究下那个函数的实现再回来备注,加油加油加油!,我一定会回来的!!!
-----添加以下global和nonlocal的用法
全局变量在函数内可以调用但是不可以修改,如果需要修改则需要在变量前面加上global。
另外一种情况:
函数里面嵌套一个函数,有一个变量名比如x。
存在一个全局变量x;
还存在一个函数内的x;
函数的嵌套函数也存在一个x。
最内部的嵌套函数想调用改变外部函数的x,又不想改变全局变量的x,此时变量名前加nonlocal即可。
见实际使用如下:
def b():
test=1234
def c():
nonlocal test
return test+1
print(c())
def d():
test=1234
def c():
global test
return test+1
print(c())
b()
d()
运行结果:
C:\Users\18566\AppData\Local\Programs\Python\Python38\python.exe F:/python/WEBAuto_pythonV3_20200619/testTmp/tmp.py
1235
124
同理globals()返回当前的全局变量,locals()返回当前scop内的变量,都是以字典的形式返回。