def foo(x,y,*args,a=1,b,**kwargs): print(x,y) print(args) print(a) print(b) print(kwargs) foo(1,2,3,4,5,b=8,c=4,d=5)
1 2
(3, 4, 5)
1
8
{'c': 4, 'd': 5}
*后定义的参数,必须被传值(有默认值的除外),且必须按照关键字实参的形式传递
x=1
def f1():
x=5 #f1的局部
def f2():
# x=4 #f2的局部
print(x)
print(locals())
return f2 #返回函数名,地址
x=100
def f3(func):
x=2 #f3的局部
func()
x=1000 #全局
f3(f1())
print(globals())
5
{'x': 5}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0043C390>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'F:/back01/hansu.py', '__cached__': None, 'x': 1000, 'f1': <function f1 at 0x003FB660>, 'f3': <function f3 at 0x021652B8>}
max=1
def f1():
max=2
def f2():
# max=3
def f3():
# global max #max=1 等于修改全局变量
nonlocal max #max=2 等于修改局部变量
max=max+4
print(max)
f3()
f2()
f1()
print(max)
6
1
def scope_test(): def do_local(): spam = "local spam" #此函数定义了另外的一个spam字符串变量,并且生命周期只在此函数内。此处的spam和外层的spam是两个变量,如果写出spam = spam + “local spam” 会报错 如果内部函数有引用外部函数的同名变量或者全局变量,并且对这个变量有修改.那么python会认为它是一个局部变量,又因为函数中没有gcount的定义和赋值,所以报错。
def do_nonlocal(): nonlocal spam #使用外层的spam变量 spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print ( "After local assignmane:" , spam) do_nonlocal() print ( "After nonlocal assignment:" ,spam) do_global() print ( "After global assignment:" ,spam) scope_test() print ( "In global scope:" ,spam) |
输出是:
After local assignmane: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam