Python Closures and Decorators
Since I, in retrospect, made the wrong choice when cutting down a Python course to four hours and messed up the decorator exercise, I promised the attendants that I'd make a post about closures and decorators and explain it better - this is my attempt to do so.
Functions are objects, too. In fact, in Python they are First Class Objects - that is, they can be handled like any other object with no special restrictions. This gives us some interesting options, and I'll try to move through them from the bottom up.
A very basic case of using the fact that functions are objects is to use them as you would a function pointer in C; pass it into another function that will use it. To illustrate this, we'll take a look at the implementation of a repeat function - that is, a function that accepts another function as argument together with a number, and then calls the passed function the specified number of times:
>>> def greeter():
... print("Hello")
...
>>> #An implementation of a repeat function
>>> def repeat(fn, times):
... for i in range(times):
... fn()
...
>>> repeat(greeter, 3)
Hello
Hello
Hello
>>>This pattern is used in a large number of ways - passing a comparison function to a sorting algorithm, passing a decoder function to a parser, and in general specializing the behaviour of a function, or passing a specific parts of a job to be done into a function that abstracts the work flow (i.e. sort() knows how to sort lists, compare() knows how to compare elements).
Functions can also be declared in the body of another function, which gives us another important tool. In the most basic case, this can be used to "hide" utility functions in the scope of the function that uses them:
... def is_integer(value):
... try:
... return value == int(value)
... except:
... return False
... for v in values:
... if is_integer(v):
... print(v)
...
>>> print_integers([1,2,3,"4", "parrot", 3.14])
1
2
3
Functions are objects, too. In fact, in Python they are First Class Objects - that is, they can be handled like any other object with no special restrictions. This gives us some interesting options, and I'll try to move through them from the bottom up.
A very basic case of using the fact that functions are objects is to use them as you would a function pointer in C; pass it into another function that will use it. To illustrate this, we'll take a look at the implementation of a repeat function - that is, a function that accepts another function as argument together with a number, and then calls the passed function the specified number of times:
CODE:
>>> #A very simple function>>> def greeter():
... print("Hello")
...
>>> #An implementation of a repeat function
>>> def repeat(fn, times):
... for i in range(times):
... fn()
...
>>> repeat(greeter, 3)
Hello
Hello
Hello
>>>This pattern is used in a large number of ways - passing a comparison function to a sorting algorithm, passing a decoder function to a parser, and in general specializing the behaviour of a function, or passing a specific parts of a job to be done into a function that abstracts the work flow (i.e. sort() knows how to sort lists, compare() knows how to compare elements).
Functions can also be declared in the body of another function, which gives us another important tool. In the most basic case, this can be used to "hide" utility functions in the scope of the function that uses them:
CODE:
>>> def print_integers(values):... def is_integer(value):
... try:
... return value == int(value)
... except:
... return False
... for v in values:
... if is_integer(v):
... print(v)
...
>>> print_integers([1,2,3,"4", "parrot", 3.14])
1
2
3
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-734440/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Angular 2 Decorators – 1Angular
- ECMAScript Decorators---裝飾器
- 【低門檻 手把手】python 裝飾器(Decorators)原理說明Python
- Draft 文件翻譯 - 高階主題 - DecoratorsRaft
- 聊聊Typescript中的設計模式——裝飾器篇(decorators)TypeScript設計模式
- 【python】python安裝Python
- python ----python的安裝Python
- python:python的多程式Python
- python--- 之The program 'python' can be found in the following packages: * python-minimal * python3PythonPackage
- Python IDLE和Python的區別!Python入門教程Python
- python學習之初識pythonPython
- 【Python】python類的繼承Python繼承
- Python 序列化(Python IO)Python
- Python合集之Python函式Python函式
- pythonPython
- python _Python
- python教程(一)·python環境搭建Python
- 學習Python的日子 Python(6)Python
- [python] Python型別提示總結Python型別
- Python補充02 Python小技巧Python
- 小白自學Python(一) -- Python教程Python
- Python之將Python字串生成PDFPython字串
- Python 字串格式化(Python IO)Python字串格式化
- Python 檔案讀寫(Python IO)Python
- 『python入門:』 python的介紹Python
- 與 Python 之父聊天:更快的 Python!Python
- python(python中的super函式、)Python函式
- python中#!/usr/bin/python與#!/usr/bin/env python的區別Python
- Python入門:Python 2與Python3有什麼區別?Python
- 學習Python選擇Python2還是Python3呢?Python
- Python學習筆記|Python之程式Python筆記
- Python 筆記-2-1-Python 概述Python筆記
- Python 微服務開發--Python Microservices DevelopmentPython微服務ROSdev
- python SQL基礎與python互動PythonSQL
- 「Python」Convert map object to numpy array in python 3PythonObject
- 【Python】阿里雲python sdk快速入門Python阿里
- Python - opencv-python 獲取影片尺寸PythonOpenCV
- Python基礎篇-Python基礎01Python
- Python基礎之Python資料世界Python