python first-class functions

From "Fluent Python"
1, - all functions in python are first-class objects:

.在运行时创建
.能赋值给变量或者数据结构中的元素
.能作为参数传给函数
.能作为函数的返回结果

The function object itself is an instance of the function class.

def hello():
    print("hello,are you fine")

h = hello #本质函数名也是变量。所以能赋值给另一便能量
h() #hello,are you fine

2. - Higher order functions:

接受函数作为参数,或者把函数所谓结果返回的函数就是高阶函数。

Such as:

import math

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

print add(25, 9, math.sqrt) #8.0
def format_name(s):
    s = s.lower()
    return s.capitalize()

print map(format_name, ['adam', 'LISA', 'barT']) 
#['Adam', 'Lisa', 'Bart']
def prod(x, y):
    return x*y

print reduce(prod, [2, 4, 5, 7, 12])
# 相当于2*4*5*7*12 。不过python3.4发现不是在全局空间里,需要导入了
#from functools import reduce
import math

def is_sqr(x):
    y = math.sqrt(x)
    return float(int(y))==y
print filter(is_sqr, range(1, 101))
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

List comprehensions and generator expressions can replace the use of map, filter, reduce

3, - anonymous function:

lambda关键字在python表达式内创建匿名函数
但是python的语法限制了lambda函数的定义体只能使用纯表达式。
换句话说lambda函数的定义体不能赋值,也不能使用whiletry等语句。
import math

w = ["strawberry",'fig','apple','cherry','raspberry','banana']
t = lambda word: word[::-1]
print(t(w)) #['banana', 'raspberry', 'cherry', 'apple', 'fig', 'strawberry']
print(sorted(w,key=t)) #['banana', 'apple', 'fig', 'raspberry', 'strawberry', 'cherry']

4, - callable object

除了用户定义的函数,调用运算符(即()符号)还可以应用到其他对象上。
如果想判断对象是否可以调用,可以使用内置函数callable()
下面是7中可调用对象。

1
) User-defined function
2) Built-in function
3) Built-in method
4) Method: that is, the function implemented in the class
5) Class:
calling the class will run the new method of the class to create an instance, and then run the init method to initialize instance, and finally return the instance.
Because there is no new operator in python, calling a class is equivalent to calling a function (usually, calling a class creates an instance of that class)
6) An instance of a class:
If a class defines a call method, then its instance can be called as a function
7) Generated Yield function:
A function or method that uses the yield keyword. Calling a generator function returns a generator object.
 

print([callable(obj) for obj in (abs,str,12)])
#[True, True, False]

5. - User-defined callable types:

任何python对象都可以表现的像函数,只要实现实例方法__call__.
import random
class BingoCage:
    def __init__(self,items):
        self._items = list(items)
        random.shuffle(self._items)
    def pick(self):
        try:
            return self._items.pop()
        except IndexError:
            raise LookupError("pick from empty BingoCage")

    def __call__(self):
        return self.pick()

bingo = BingoCage(range(10))
print(bingo.pick()) #一般常见调用方式
#下面是实现了__call__方法的调用方式:
print(bingo())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325484692&siteId=291194637