Python 学习笔记(三)Function
python引用變量的順序: 當(dāng)前作用域局部變量->外層作用域變量->當(dāng)前模塊中的全局變量->python內(nèi)置變量
1. Scope:
? If a variable is assigned inside a def, it is local to that function.
? If a variable is assigned in an enclosing def, it is nonlocal to nested functions.
? If a variable is assigned outside all defs, it is global to the entire file.
? global makes scope lookup begin in the enclosing module’s scope and allows
names there to be assigned. Scope lookup continues on to the built-in scope if the
name does not exist in the module, but assignments to global names always create
or change them in the module’s scope.
? nonlocal restricts scope lookup to just enclosing defs, requires that the names already
exist there, and allows them to be assigned. Scope lookup does not continue
on to the global or built-in scopes.
global關(guān)鍵字用來在函數(shù)或其他局部作用域中使用全局變量。但是如果不修改全局變量也可以不使用global關(guān)鍵字。
>>> gcount = 0 >>> def func(): ... print(gcount) ... >>> def func_count(): ... global gcount ... gcount +=1 ... return gcount ... >>> def func_count_test(): ... print(func_count()) ... print(func_count()) 1 2nonlocal關(guān)鍵字用來在函數(shù)或其他作用域中使用外層(非全局)變量。
>>> def tester(start): ... state = start # Each call gets its own state ... def nested(label): ... nonlocal state # Remembers state in enclosing scope ... print(label, state) ... state += 1 # Allowed to change it if nonlocal ... return nested ... >>> F = tester(0) >>> F('spam') # Increments state on each call spam 0 >>> F('ham') ham 1 >>> F('eggs') eggs 2 >>> spam = 99 >>> def tester(): ... def nested(): ... nonlocal spam # Must be in a def, not the module! ... print('Current=', spam) ... spam += 1 ... return nested ... SyntaxError: no binding for nonlocal 'spam' found2. Arguments
- Immutable arguments are effectively passed “by value.” (int,string,tuple) (復(fù)制)
- Mutable arguments are effectively passed “by pointer.” (list, dictionary) (引用)
參數(shù)傳遞:*代表的是tuple,**代表map
>>> def echo(*args, **kwargs): print(args, kwargs) ... >>> echo(1, 2, a=3, b=4) (1, 2) {'a': 3, 'b': 4}intersect and union:
def intersect(*args):res = []for x in args[0]: # Scan first sequencefor other in args[1:]: # For all other argsif x not in other: break # Item in each one?else: # No: break out of loopres.append(x) # Yes: add items to endreturn res def union(*args):res = []for seq in args: # For all argsfor x in seq: # For all nodesif not x in res:res.append(x) # Add new items to resultreturn res?
轉(zhuǎn)載于:https://www.cnblogs.com/zyf7630/p/3093279.html
總結(jié)
以上是生活随笔為你收集整理的Python 学习笔记(三)Function的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决scrollViewDidScrol
- 下一篇: Python编程系列教程第13讲——隐藏