File tree 2 files changed +65
-0
lines changed
2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -341,3 +341,68 @@ def factorial(n):
341
341
print ()
342
342
343
343
#嵌套函数_内部函数_数据隐藏
344
+ def outer ():
345
+ print ("outer running" )
346
+
347
+ def inner ():
348
+ print ("inner running" )
349
+ inner ()
350
+
351
+ outer ()
352
+ # inner() # 报错,因为inner是一个局部函数,只能在outer函数中调用
353
+
354
+
355
+ def printName (isChinese ,name ,familyName ):
356
+
357
+ def inner_print (a ,b ):
358
+ print ("{0} {1}" .format (a ,b ))
359
+ if isChinese :
360
+ inner_print (familyName ,name )
361
+ else :
362
+ inner_print (name ,familyName )
363
+
364
+ printName (True ,"小明" ,"张" )
365
+ printName (False ,"Tom" ,"Smith" )
366
+
367
+ # nonlocal和global关键字
368
+ a = 100
369
+
370
+ def outer ():
371
+ b = 10
372
+
373
+ def inner ():
374
+ nonlocal b # nonlocal关键字,用于在局部函数中修改外部函数的局部变量
375
+ print ("inner b=" ,b )
376
+ b = 20
377
+
378
+ global a # global关键字,用于在局部函数中修改全局变量
379
+ a = 200
380
+
381
+ inner ()
382
+
383
+ print ("outer b=" ,b )
384
+ outer ()
385
+ print ("a=" ,a )
386
+
387
+ print ("*" * 100 )
388
+ print ()
389
+
390
+ # LEGB规则 -- 作用域的查找顺序--局部变量、外部函数的变量、全局变量、内置变量
391
+ s = 'global'
392
+ def outer ():
393
+ # s = "outer"
394
+
395
+ def inner ():
396
+ # s = "inner"
397
+ print (s )
398
+
399
+ inner ()
400
+ outer ()
401
+
402
+
403
+
404
+
405
+
406
+
407
+
408
+
You can’t perform that action at this time.
0 commit comments