Quick actions

cmd+k|ctrl+k

Navigation

Languages

closure --> decrorator

Snippet info

Language

Python

Visibility

public

Author

kachuntong01

Created

2025-06-24T06:20:26.277994Z

Updated

2025-06-24T06:22:18.395791Z

def counter(fn):
    count = 0
    def inner(*args, **kwargs):
        nonlocal count
        count += 1
        print(f'function fn address at',fn)
        print('Function {0} was called {1} times' .format(fn.__name__, count))
        return fn(*args, **kwargs) ## argument and keyword argument
    return inner
    
def add(a, b=0):
    return a + b
def diff(a, b=0):
    return a - b    
print(f'function add address at',add)
add = counter(add)
print(f'function add address after counter at',add)
diff = counter(diff)

print(add (1,2))
print(diff(2,3))
print(add(3,4))
print(diff(6,7))
# count and fn are the closure, everytime, the function fn {"add"pass into fn} run, count + 1
# everytime count and (fn  <---"add") , inner function's address retained, keep the count and fn as closures.
print(dir(add))
INFO