Inner function closure 4

Run Settings
LanguagePython
Language Version
Run Command
def counter(fn): count = 0 def inner(*args, **kwargs): nonlocal count #話比python知唔係inner內部(local)的varibles count += 1 print('Function {0} was called {1} times'.format(fn.__name__, count)) return fn(*args, **kwargs) #add function 黎左呢度 return inner def add(a, b=0): #a is neccessary b default = 0 return a + b add = counter(add) #(add) is inside inner closure and now (add) --> (fn) counter(fn) assign 左比add result = add(1,2) #result = 3 (1+2) # result = add(1,2) --> result = counter(fn)(1,2) --> inner(1,2) #1,2 as *arg **kwargs is empty #count 0+1=1 ; print('Function {0} was called {1} times'.format(fn.__name__, count)) 會印出Function add was called 1 times #fn.__name__ 是add 即{0} <-- 0號位 count = 1 即{1} <--1號位 #return fn(*args, **kwargs) => fn(1,2) *args is now emtpy (a=1, b=2) is **kwargs => 1->a 2->b 所以result = 1+2 = 3
Editor Settings
Theme
Key bindings
Full width
Lines