小菜鸟的代码世界 2020-02-20
name = '月月' def fun2(): name = '小月月' name += '会弹吉他' print(name) fun2()
小月月会弹吉他
name = '月月' def fun2(): print(name) name += '会弹吉他' fun2()
只是获取不需要加
name = '月月' def fun2(): global name name += '会弹吉他' print(name) fun2() print(name)
月月会弹吉他 月月会弹吉他
list1 = ['python','php','go'] def fun2(): list1.append('java') fun2() print(list1)
['python', 'php', 'go', 'java']
a = 10 def func1(): b = 20 def func2(): print(a,b) func2() func1()
10 20
list1 = ['python','php','go'] def func1(): list2 = ['html','css'] def func2(): list1.append('java') list2.append('javascript') print(list1,list2,sep='\n') func2() func1()
['python', 'php', 'go', 'java'] ['html', 'css', 'javascript']
a = 10 def func1(): b = 20 def func2(): global a a += b print(a,b) func2() func1()
a = 10 def func1(): b = 20 def func2(): nonlocal b b += a print(a,b) func2() func1()
4.1, locals(),可以看到当前函数中声明的变量有哪些,以字典的形式输出
a = 10 def func1(): b = 20 def func2(): nonlocal b b += a print(locals()) func2() print(locals()) func1()
{'b': 30} {'func2': <function func1.<locals>.func2 at 0x000001BF232F4730>, 'b': 30}
a = 10 def func1(): b = 20 def func2(): nonlocal b b += a print(globals()) func2() func1()