閉包 Closure

閉包 Closure

Posted by 劉啟仲 on Friday, December 25, 2020
string ='global'
def assignment():
  string = 'Enclosd' # Enclosd
  def inner():
    print(string) #local
  return inner

func = assignment()
print(func) # <function assignment.<locals>.inner at 0x000001AED30AAF28>
func() # Enclosd
print(string) # global

在最後的print(string)中,不會因為呼叫了func( )而使得最後的輸出被修改,assignment中的變數,不會因為在外層呼叫而漏致外層。

當一個巢狀方法 (nested function),需要用到 enclosd 區間,則會將他一起打包出來。

string ='global'
def assignment():
  class Superman:
    def __init__(self):
      print('I am Superman')
      
  string = 'Enclosd' # Enclosd
  
  def inner1():
    print('inner1')
    
  def inner2():
    print(string)
    inner1()
    man = Superman()
  return inner2

func = assignment()
func() 
# Enclosd
# inner1

print(func.__closure__) # 可以列出打包的東西
# (<cell at 0x107236fd0: type object at 0x7f98c9b04360>, <cell at 0x107236fa0: function object at 0x107247430>, <cell at 0x107236f10: str object at 0x10724cd30>)

閉包就是保護與偷渡的角色。

閉包特色:

  • 可降低global var使用
  • 在function的scope外使用function
  • 造就decorator