函数
高阶函数
高阶函数:一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归),满足其一则为高阶函数。
参数为函数
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)
闭包
形成闭包的条件
- 函数嵌套
- 将内部函数作为返回值返回
- 内部函数必须要使用到外部函数变量
简单来说就是一个函数定义中引用了函数外定义的变量,并且该函数可以在其定义环境外被执行。这样的一个函数我们称之为闭包。实际上闭包可以看做一种更加广义的函数概念。因为其已经不再是传统意义上定义的函数。
装饰器
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]