2012-08-28 171 views
1

我是Python的新手,我對shutil模塊中下面提到的代碼片段的工作有些疑問。從Python中的函數返回函數

def ignore_patterns(*patterns): 
    """Function that can be used as copytree() ignore parameter. 

    Patterns is a sequence of glob-style patterns 
    that are used to exclude files""" 
    def _ignore_patterns(path, names): 
     ignored_names = [] 
     for pattern in patterns: 
      ignored_names.extend(fnmatch.filter(names, pattern)) 
     return set(ignored_names) 
    return _ignore_patterns 

何時shutil.copytree呼叫與ignore選項設置爲ignore_patterns發,然後調用ignore_patterns功能和返回功能。我的疑惑是:

1)ignore_patterns當被調用時會返回_ignore_pattern函數的引用。現在,當這個函數被調用時,它如何訪問「模式」列表?一旦被調用的函數「ignore_patterns」已經返回,那麼在其調用中創建的列表模式應該只能用於其被調用的作用域。

2)返回函數_ignore_patterns函數名稱中下劃線的含義是什麼?

回答

4

這被稱爲closure,它是允許嵌套函數的語言的一般特徵。內的功能可以在一個外部範圍接近過變量,並且將保留該名稱的參考當它們從外函數外調用。

下劃線只是表示_ignore_patterns是一個內部函數,同時保持返回函數的名稱相似。它可以被稱爲任何你喜歡的。

1
  • ignore_patterns稱爲將返回_ignore_pattern函數引用時。現在當這個函數被調用時,它是如何訪問「模式」列表的。

    這很好。 _ignore_pattern是關閉。這意味着它圍繞所有需要完成其工作的局部變量(包括函數參數)。垃圾收集器最終會得到它,但不是在它可能仍然需要的時候。

  • 返回函數中下劃線的意義是什麼_ignore_patterns函數名?

    筆者只是想消除歧義的名字。這可難倒了調用關閉f。這是我會做的。