python 学习笔记三(高阶函数)

** 高阶函数:接受函数作为参数,or 把函数作为返回结果; eg:map

from operator import mul
from functools import partial
triple = partial(mul, 3) # 使用 mul 创建 triple 函数,把第一个定位参数定为 3。
triple(7) 
#21
list(map(triple, range(1, 10))) # 在 map 中使用 triple;在这个示例中不能使用 mul。
# [3, 6, 9, 12, 15, 18, 21, 24, 27]

 

**  调用类:1)运行 __new__创建(构造)一个实例 2)运行 __init__ 初始化实例,返回给调用方

  ==》相当于调用函数;

  ==》覆盖 __new__ 方法的话,也可能出现其他行为

  ==》如果类定义了 __call__ 方法,那么它的实例可以作为函数调用

 ** 函数的参数【定位参数--》仅限关键字参数】

def tag(name, *content, cls=None, **attrs):
    """生成一个或多个HTML标签"""
    if cls is not None:
        attrs['class'] = cls
    if attrs:
        attr_str = ''.join(' %s="%s"' % (attr, value)
                        for attr, value
                            in sorted(attrs.items()))
     else:
        attr_str = ''
    if content:
        return '\n'.join('<%s%s>%s</%s>' %
            (name, attr_str, c, name) for c in content)
    else:
        return '<%s%s />' % (name, attr_str)

 

posted @ 2021-06-15 09:03  小毛编  阅读(52)  评论(0编辑  收藏  举报