第十四天 Python 函数后续(高阶函数)

函数

高阶函数

高阶函数:一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归),满足其一则为高阶函数。

参数为函数
def bar():
    print("in the bar..")
def foo(func):
    func()
    print("in the foo..")

foo(bar)
返回值为函数
def bar():
    print("in the bar..")
def foo(a):
    print("in the foo..")
    return bar
print('='*30)
res = foo(bar)
print('='*30)
print(res)
print('='*30)
res()
print('='*30)
ba = 1
foo(ba)()
print('='*30)
foo(ba)
print('='*30)

这个返回值为函数我要分解一下

在这里插入图片描述
上面的foo(ba)实际上就是执行了foo()函数

以上两个示例中,函数foo()为高阶函数,示例一中函数bar作为foo的参数传入,示例二中函数bar作为foo的返回值。

注:函数名(例如bar 、foo)–>其为该函数的内存地址;函数名+括号(例如 bar()、foo() )–>调用该函数。

匿名函数

匿名函数(lambda)是指没有名字的函数,应用在需要一个函数但是又不想费神去命名这个函数的场合。通常情况下,这样的函数只使用一次。

resuult = lambda [arg1 [,arg2,...,argn]]:expression
- resuult:用于调用lambda表达式。
- [arg1 [,arg2,...,argn]]:可选参数,用于指定要传递的参数列表,多个参数间使用逗号分隔。
- expression:必须参数,用于指定一个实现具体功能的表达式。如果有参数,那么在该表达式中将应用这些参数。

使用lambda表达式时,参数可以有多个,用逗号分隔,但是表达式只能有一个,即只能返回一个值,而且也不能出现其他非表达语句(如for或while)

闭包

在这里插入图片描述
形成闭包的条件

  1. 函数嵌套
  2. 将内部函数作为返回值返回
  3. 内部函数必须要使用到外部函数变量

简单来说就是一个函数定义中引用了函数外定义的变量,并且该函数可以在其定义环境外被执行。这样的一个函数我们称之为闭包。实际上闭包可以看做一种更加广义的函数概念。因为其已经不再是传统意义上定义的函数。

装饰器

python装饰器(fuctional decorators)就是用于拓展原来函数功能的一种函数,目的是在不改变原函数名(或类名)的情况下,给函数增加新的功能。

这个函数的特殊之处在于它的返回值也是一个函数,这个函数是内嵌“原“”函数的函数。

class staticmethod(object):
    """
    staticmethod(function) -> method
    
    Convert a function to be a static method.
    
    A static method does not receive an implicit first argument.
    To declare a static method, use this idiom:
    
         class C:
             @staticmethod
             def f(arg1, arg2, ...):
                 ...
    
    It can be called either on the class (e.g. C.f()) or on an instance
    (e.g. C().f()). Both the class and the instance are ignored, and
    neither is passed implicitly as the first argument to the method.
    
    Static methods in Python are similar to those found in Java or C++.
    For a more advanced concept, see the classmethod builtin.
    """
    def __get__(self, *args, **kwargs): # real signature unknown
        """ Return an attribute of instance, which is of type owner. """
        pass

    def __init__(self, function): # real signature unknown; restored from __doc__
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    __func__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    __isabstractmethod__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default


    __dict__ = None # (!) real value is "mappingproxy({'__get__': <slot wrapper '__get__' of 'staticmethod' objects>, '__init__': <slot wrapper '__init__' of 'staticmethod' objects>, '__new__': <built-in method __new__ of type object at 0x00007FFC7D8C1910>, '__func__': <member '__func__' of 'staticmethod' objects>, '__isabstractmethod__': <attribute '__isabstractmethod__' of 'staticmethod' objects>, '__dict__': <attribute '__dict__' of 'staticmethod' objects>, '__doc__': 'staticmethod(function) -> method\\n\\nConvert a function to be a static method.\\n\\nA static method does not receive an implicit first argument.\\nTo declare a static method, use this idiom:\\n\\n     class C:\\n         @staticmethod\\n         def f(arg1, arg2, ...):\\n             ...\\n\\nIt can be called either on the class (e.g. C.f()) or on an instance\\n(e.g. C().f()). Both the class and the instance are ignored, and\\nneither is passed implicitly as the first argument to the method.\\n\\nStatic methods in Python are similar to those found in Java or C++.\\nFor a more advanced concept, see the classmethod builtin.'})"

上面的有点复杂

那就来点简单的吧

在这里插入图片描述
数字2也是引用装饰器,@deco是使用装饰器

递归函数

使用递归,在函数内部调用自己
递归没有结束条件,一定要自己设定结束条件
能够用递归实现的,都可以用循环实现,递归效率低所以很好少使用

在这里插入图片描述

内置函数

map()
  • 描述
    map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

  • 语法
    map() 函数语法:
map(function, iterable, ...)
  • 参数
    function – 函数
    iterable – 一个或多个序列
  • 返回值
    Python 2.x 返回列表。
    Python 3.x 返回迭代器。
>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
filter()
  • 描述
    filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

注意: Python2.7 返回列表,Python3.x 返回迭代器对象,具体内容可以查看:Python3 filter() 函数

  • 语法
    以下是 filter() 方法的语法:
filter(function, iterable)
  • 参数
    function – 判断函数。
    iterable – 可迭代对象。

  • 返回值
    返回列表。

  • 实例
    以下展示了使用 filter 函数的实例:

过滤出列表中的所有奇数:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

输出结果 :

[1, 3, 5, 7, 9]

过滤出1~100中平方根是整数的数:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
 
newlist = filter(is_sqr, range(1, 101))
print(newlist)

输出结果 :

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Asahi_aileen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值