一、一等对象
Python函数是一等对象,其满足以下4个条件:
1. 在运行时创建
2.能赋值给变量或数据结构中的元素
3.能作为参数传递给函数
4.能作为函数的返回结果
二、代码示例
1、函数视为对象
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 15:19
# @Author  : Maple
# @File    : 01-函数视为对象.py
# @Software: PyCharm
def fun(a):
    """return一个整数"""
    return a
if __name__ == '__main__':
    print(fun.__doc__) # return一个整数
    # 函数fun的类型是function类的一个实例对象
    print(type(fun)) # <class 'function'>
2、高阶函数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 15:22
# @Author  : Maple
# @File    : 02-高阶函数.py
# @Software: PyCharm
"""高阶函数是指 接受函数作为参数 或者把函数作为结果返回的函数
 1.高阶函数是函数
 2.高阶函数接受函数作为参数或者函数作为返回结果
"""
def f1(a):
    return a * 2
if __name__ == '__main__':
    #1. sorted就是一个高阶函数,参数key接受一个函数作为参数,然后对`可迭代对象`按照指定的规则进行排序
    fruits = ['bigpear','apple','banana','cherry']
    sorted_fruite = sorted(fruits,key=len)
    print(sorted_fruite) # ['apple', 'banana', 'cherry', 'bigpear']
    #2.高阶函数map示例
    # 对[0-4]之间的每个数应用f1函数,并返回结果
    print(list(map(f1,range(5)))) # [0, 2, 4, 6, 8]
    # 列表推导式的替代方案
    r1 = [f1(i) for i in range(5)]
    print(r1) # [0, 2, 4, 6, 8]
    #3.高阶函数filter示例
    print(list(map(f1,filter(lambda x: x%2,range(6))))) # [2, 6, 10]
    # 列表推导式的替代方案
    r2 = [f1(i) for i in range(6) if i % 2]
    print(r2) #[2, 6, 10]
3、可调用对象
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 15:34
# @Author  : Maple
# @File    : 03-可调用对象.py
# @Software: PyCharm
"""Python数据模型中的7种可调用对象
1.用户定义的函数:使用def语句或者lambda表达式创建
2.内置函数,如len
3.内置方法,如dict.get
4.方法:在类中定义的函数
5.类
6.类的实例
7.生成器函数
"""
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')
    # 内置call方法,实现BingoCage类的实例是可调用的
    def __call__(self):
        return self.pick()
if __name__ == '__main__':
    # 1.使用callable判断对象 是否可调用
    r1 = [callable(obj) for obj in (abs,str,12)]
    print(r1) # [True, True, False]
    # 2. 判断自定义类的实例是否可调用
    bingo = BingoCage(range(3))
    # 实例对象是可调用对象
    print(callable(bingo)) # True
    # 实例对象是可调用的
    r= bingo()
    print(r) # 0
4、仅限关键字参数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 14:56
# @Author  : Maple
# @File    : 04-仅限关键字参数.py
# @Software: PyCharm
def tag(name,*content,cls=None,**attrs):
    """生成一个或多个html标签"""
    if cls is not None:
        attrs['class'] = cls
    if attrs:
        attrs_str = ''.join(' %s="%s"' %(attr,value)
                                 for attr,value in sorted(attrs.items()))
    else:
        attrs_str = ''
    if content:
        return '
'.join('<%s%s>%s</%s>' %(name,attrs_str,c,name)
                                       for c in content)
    else:
        return '<%s%s />' %(name,attrs_str)
def f(a,*,b):
    """函数参数中间放了一个*,调用函数时必须以关键字参数的形式传入b的值"""
    return a,b
if __name__ == '__main__':
    #1.tag标签测试
    ## 1-1 案例1
    html1 = tag('br')
    print(html1) # <p>hello</p>
    ## 1-2 案例2
    html2 = tag('p','hello')
    print(html2) # <p>hello</p>
    ## 1-3 案例3
    html3 = tag('p','Java','world')
    """
    <p>Java</p>
    <p>world</p>
    """
    print(html3)
    ## 1-4 案例4
    html4 = tag('p','hello','world',cls='size')
    """
    <p class="size">hello</p>
    <p class="size">world</p>
    """
    print(html4)
    ## 1-5 案例5
    my_tag = {'name':'img', 'title':'Sunset',
              'src': 'sunset.jpg', 'cls': 'framed'}
    html5 = tag(**my_tag)
    print(html5) # <img class="framed" src="sunset.jpg" title="Sunset" />
    #2.函数f测试
    #  TypeError: f()takes 1 positional argument but 2 were given
    # f(1,3)
    a, b = f(1,b= 1)
    print(a,b) # 1 1
5、函数参数信息获取
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 16:02
# @Author  : Maple
# @File    : 05-函数参数信息获取.py
# @Software: PyCharm
def tag(name,*content,cls=None,**attrs):
    """生成一个或多个html标签"""
    if cls is not None:
        attrs['class'] = cls
    if attrs:
        attrs_str = ''.join(' %s="%s"' %(attr,value)
                                 for attr,value in sorted(attrs.items()))
    else:
        attrs_str = ''
    if content:
        return '
'.join('<%s%s>%s</%s>' %(name,attrs_str,c,name)
                                       for c in content)
    else:
        return '<%s%s />' %(name,attrs_str)
if __name__ == '__main__':
    from inspect import signature
    # 1. 获取函数参数信息
    sig = signature(tag)
    print(type(sig)) # 返回一个inspect.Signature类的实例对象
    print(str(sig)) # (name, *content, cls=None, **attrs)
    # inspect.Signature对象有一个parameters属性,将参数名与inspect.Parameter对象对应起来,同时各个Parameter对象也有自己的属性,包括name,default,kind
    # 如下示例:name是参数名,param是Parameter对象,该对象封装了参数的name(参数名),default(参数默认值)和kind(参数类型)属性
    for name,param in sig.parameters.items():
        """打印结果
        POSITIONAL_OR_KEYWORD : name = <class 'inspect._empty'>
        VAR_POSITIONAL : content = <class 'inspect._empty'>
        KEYWORD_ONLY : cls = None
        VAR_KEYWORD : attrs = <class 'inspect._empty'>
        """
        """补充说明
         POSITIONAL_OR_KEYWORD代表`定位参数和关键字参数`
         VAR_POSITIONAL代表`定位参数元组`
         KEYWORD_ONLY代表`仅限关键字参数`
         inspect._empty表示没有默认值
        """
        print(param.kind,':',name,'=',param.default)
    # 2.给函数形参 绑定实参
    my_tag = {'name': 'img', 'title': 'Sunset',
              'src': 'sunset.jpg', 'cls': 'framed'}
    bound_args = sig.bind(**my_tag)
    for name,value in bound_args.arguments.items():
        """打印结果
        name = img
        cls = framed
        attrs = {'title': 'Sunset', 'src': 'sunset.jpg'}
        """
        print(name,'=',value)
    del my_tag['name']
    # TypeError: missing a required argument: 'name'
    # 因为name是必须传递的参数,却没有传入
    # bound_args = sig.bind(**my_tag)
6、函数注解
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 21:48
# @Author  : Maple
# @File    : 06-函数注解.py
# @Software: PyCharm
"""
1. 函数声明的各个参数可以在:之后增加注解表达式
2. 如果参数有默认值,注解放在参数和'='之间,如本例中的'int>0'
3. 如果想注解返回值,可以在)和':' 之间田间->和一个表达式,如本例的 ->str
"""
def clip(text:str,max_len:'int>0'=80) ->str:
    """在max_len前面或后面的第一个空格处截断文本"""
    end = None
    if len(text) > max_len:
        space_before = text.rfind(' ',0, max_len)
        # 如果能够找到space
        if space_before >=0:
            end = space_before
        else:
            space_after = text.rfind('' ,max_len)
            if space_after >= 0:
                end = space_after
    if end is None: # 没找到空格
        end = len(text)
    return text[:end].rstrip()
if __name__ == '__main__':
    # 获取函数注解信息
    print(clip.__annotations__) # {'text': <class 'str'>, 'max_len': 'int>0', 'return': <class 'str'>}
    # 从函数签名中获取注解信息
    from inspect import signature
    sig = signature(clip)
    # 打印注解返回值
    print(sig.return_annotation) #<class 'str'>
    # 打印参数注解
    for param in sig.parameters.values():
        # sig.parameters有一个属性annotation,里面封装了参数注解值
        note = repr(param.annotation).ljust(13)
        """打印结果
        <class 'str'> : text = <class 'inspect._empty'>
        'int>0'       : max_len = 80
        """
        print(note,':', param.name,'=', param.default)
7、函数式编程包
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 22:03
# @Author  : Maple
# @File    : 07-函数式编程包.py
# @Software: PyCharm
from functools import reduce
from operator import mul
# operator模块
def fact(n):
    # 计算n!
    return reduce(mul,range(1,n+1))
if __name__ == '__main__':
    # 1. operator模块中的mul应用
    r1= fact(5)
    print(r1) # 120
    # 2. operator模块中的itemgetter应用
    metro_data = [('Tokyo','JP',36.933,(35.689722,139.691667)),
                  ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
                  ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
                  ]
    from operator import itemgetter
    """
    itemgetter(1)等价于:lambda x: x[1]
    """
    for city in sorted(metro_data,key=itemgetter(1)):
        print(city)
    print('------------------------')
    # cc_name是一个函数,等价于lambda x: (x[1],x[0])
    cc_name = itemgetter(1,0)
    for city in metro_data:
        """打印结果:       
        ('JP', 'Tokyo')
        ('IN', 'Delhi NCR')
        ('MX', 'Mexico City')
        """
        # 调用cc_name
        print(cc_name(city))
    print('------------------------')
    # 3. operator模块中的attrgetter应用
    # 相比itemgetter,attrgetter能够获取嵌套属性的值
    from collections import namedtuple
    LatLong = namedtuple('LatLong','lat long')
    city_info = [('Tokyo', 'JP', (35.689722, 139.691667)),
                  ('Delhi NCR', 'IN',  (28.613889, 77.208889)),
                  ('Mexico City', 'MX', (19.433333, -99.133333)),
                  ]
    City = namedtuple('Citys','name country coord')
    citys = [City(name,country, LatLong(coord[0],coord[1])) for name,country,coord in city_info]
    # 提取第一座城市的维度
    print(citys[0].coord.lat) # 35.689722
    from operator import attrgetter
    # 自定义attrgetter:name_lat,其等价于lambda x: (x.name,x.coord.lat)
    name_lat = attrgetter('name','coord.lat')
    for city in citys:
        """打印结果
        ('Tokyo', 35.689722)
        ('Delhi NCR', 28.613889)
        ('Mexico City', 19.433333)
        """
        # 调用name_lat
        print(name_lat(city))
    # 4. operator模块中的methodcaller应用(类似于Java中的反射)
    from operator import methodcaller
    # f具备的功能是:替换空格为'-'
    f = methodcaller('replace',' ','-')
    s = 'Hello world'
    print(f(s)) # Hello-world
8、高阶函数partial
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/22 19:42
# @Author  : Maple
# @File    : 08-高阶函数partial.py
# @Software: PyCharm
"""
接受一个函数作为参数,然后创建一个新的可调用对象,把原函数的某些参数固定
"""
from functools import partial
from operator import mul
# mul函数的功能是计算两个数的乘积
# 以下方式将mul的第一个参数固定为3
triple = partial(mul,3)
if __name__ == '__main__':
    # 1. triple调用:3 * 4
    print(triple(4)) # 12
    # 2.map只能接受 单一参数的函数,所以并不能传递mul作为参数.这里也演示了partial的一个应用场景
    print(list(map(triple,range(1,10)))) # [3, 6, 9, 12, 15, 18, 21, 24, 27]
    # 字符规范化(可参考第4章字符串规范化部分)的应用场景举例
    import unicodedata
    # 定义一个nfc函数,默认参数是'NFC'
    nfc = partial(unicodedata.normalize,'NFC')
    s1 = 'café'
    s2 =  'cafeu0301'
    print(nfc(s1) == nfc(s2)) # True
    ## 补充: 原生的写法
    unicodedata.normalize('NFC',s1) == unicodedata.normalize('NFC',s2)