Python系列10——高級函數特性

目錄

 

一、Python中的函數名

二、python中的內建高階函數

1、map

2、reduce

3、filter

4、sorted

三、閉包(函數定義在函數內部,並返回函數)

四、裝飾器


一、Python中的函數名

總結:函數名就是存儲空間內一段程序的首地址。python的函數名就是指向函數的變量,可以將函數名賦值給變量,通過變量實現函數的調用。同時,也可以將函數名作爲實參,這種函數稱之爲高階函數

>>> abs(-3)
3
>>> my_abs = abs

>>> type(my_abs)

<class 'builtin_function_or_method'>
>>> my_abs(-8)

8
def add(x, y, f):
    return f(x) + f(y)

print(add(-5, 6, abs))

#輸出結果: 11

二、python中的內建高階函數

1、map

 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
# map()函數接受兩個參數,一個是函數,一個是iterable(可迭代對象)。map將傳入的函
# 數依次作用到序列的每個元素,並把結果作爲新的iterator返回。
>>> map(abs, [1, 2, 3, 4, 5])
<map object at 0x00000259C57CB128>
>>> t= map(abs, [1, 2, 3, 4, 5])
>>> tuple(t)
(1, 2, 3, 4, 5)

>>> next(t)
1
>>> next(t)
2
# 返回的t是惰性計算

2、reduce

reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

reduce把一個函數作用在一個序列上,這個函數必須接收兩個參數。reduce把結果繼續和序列的下一個元素做累積計算。

>>> res = reduce(lambda x, y: x*y, [1, 3, 5, 7, 9])
>>> res
945

3、filter

python內建的filter
 

 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.

和map()一樣,filter也接收一個函數和一個iterable(可迭代對象)。但是filter把function依次作用在可迭代對象每個元素。根據返回值是True還是False決定保留還是丟棄元素。返回同樣也是一個迭代器。

4、sorted

sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.

返回一個新的數列,數列的內容按照升序排列。還可以接收key函數,進行自定義排序。reverse爲false時,升序排列,reverse=True時,降序排列。

以上幾個函數的形參均可以接收函數,因此,都是高階函數。

三、閉包(函數定義在函數內部,並返回函數)

def my_sum(*args):
    # 在函數內部定義函數inner_sum()
    def inner_sum():
        sum_ = 0
        for i in args:
            sum_ += i
        return sum_
    return inner_sum

# 運行到此處時,調用了my_sum函數,但是並未調用inner_sum,故直接跳轉到return inner_sum,返回一個函數
f = my_sum(1, 2, 3, 6, 4, 8, 2)
# 該行代碼對inner_sum進行了調用,並最終return sum_
f()
def count():
    fs = []
    for i in range(1, 4):
        def f():
            return i*i
        fs.append(f)
    return fs

# (1)調用count()函數 (2)初始化fs (3)for循環,爲列表fs添加函數f. 
# (4)for循環結束,返回列表fs (5)解包,將fs列表中的函數分別賦值給變量f1,f2,f3
f1, f2, f3 = count()
# 調用f(),此時局部變量i的值已經變爲3,因此三個函數均return 3*3,即9
f1()
f2()
f3()

四、裝飾器@語法糖

裝飾器就是通過給函數增加功能的工具。這種方法可以不用修改函數的定義,便能增強函數的功能。

def log(func):
    def wrapper(*args, **kwargs):
        print("call %s():" % func.__name__)
        return func(*args, **kwargs)
    return wrapper


# 相當於now = log(now),使用@可以代表該語句
@log     
def now():
    print("革命尚未成功,同志仍需努力")


# 1 將now作爲形參傳遞給func(func指向原來的now),並調用該函數,返回值爲wrapper,並將返回值賦值#   給now,使得now指向新的函數wrapper 
# 2 此時now指向新函數wrapper,now()相當於wrapper()。
# 3 調用wrapper
# 4 在return語句中調用原來的func(),即now().


# 輸出結果
#         call now():
#         革命尚未成功,同志仍需努力
def log(text):

    # 此時的func指向的是的now--------------------------
    def decorator(func):    
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator

@log('execute')
def now():
    print('2015-3-25')

# 裝飾過後的now指向的是wrapper------------------------
now()

# 輸出結果
#         execute now():
#         2015-3-25

now.__name__
# 輸出結果: wrapper

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章