python一等函数

来自《流畅的python》
1、——在python中所有函数都是一等对象:

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

函数对象本身是function类的实例。

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

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

2、——高阶函数:

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

如:

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]

列表推导式和生成器表达式可以替代map、filter、reduce的使用

3、——匿名函数:

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()。
下面是7中可调用对象。

···
1)用户定义的函数
2)内置函数
3)内置方法
4)方法:即类中实现的函数
5)类:
调用类是会运行类的new方法创建一个实例,然后运行init方法,初始化实例,最后把实例返回。
因为python中没有new运算符,所以调用类相当于调用函数(通常,调用类会创建那个类的实例)
6)类的实例:
如果类定义了call方法,那么它实例可以作为函数调用
7)生成器函数:
使用yield关键字的函数或方法。调用生成器函数返回的是生成器对象。
···

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

5、——用户定义的可调用类型:

任何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())

猜你喜欢

转载自blog.csdn.net/baidu_36831253/article/details/80011319