3 回答

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
def make_printer(msg): def printer(): print msg return printer printer = make_printer('Foo!')printer()
make_printer
printer
msg
printer
msg
make_printer
訪問包含作用域的本地變量, 在超出該范圍的范圍內(nèi)執(zhí)行時(shí),
def make_printer(msg): def printer(msg=msg): print msg return printer printer = make_printer("Foo!")printer() #Output: Foo!
printer
msg
printer
make_printer
msg
printer

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
function initCounter(){ var x = 0; function counter () { x += 1; console.log(x); }; return counter;}count = initCounter();count(); //Prints 1count(); //Prints 2count(); //Prints 3
def initCounter(): x = 0; def counter (): x += 1 ##Error, x not defined print x return counter count = initCounter();count(); ##Errorcount();count();
更新
1.global
2.nonlocal
3.Object
class Object(object): pass
Object scope
initCounter
def initCounter (): scope = Object() scope.x = 0 def counter(): scope.x += 1 print scope.x return counter
scope
scope
4.x = [0]
x[0] += 1
x
5.x
counter
def initCounter (): def counter(): counter.x += 1 print counter.x counter.x = 0 return counter
添加回答
舉報(bào)