Python基础10-函数1(偏函数/高阶函数/返回函数/匿名函

2018-05-10  本文已影响78人  Jacob_LJ
Python基础-函数

1 偏函数

import functools
newFunc = functools.partial(函数名, 特定参数 = 偏爱值)

原函数:
def test(a, b, c, d=1):
    print(a + b + c + d)

创建偏函数:
newFunc = functools.partial(test, c=5)

调用偏函数
newFunc(1, 2)

偏函数就是创建不同默认值的函数,当然自己也可以手写一个,如:

def test2(a, b, c=2, d=1):
    test(a, b, 2,)
  1. 封装系统原有函数:
numStr = "100010"
result = int(numStr, base=2)
print(result)

# 将上述 int 函数封装成默认以2进制为 base 的扩展函数
import functools
int2 = functools.partial(int, base=2)
print(int2(numStr))

2 高阶函数

def caculate(num1, num2, caculateFunc):
    result = caculateFunc(num1, num2)
    print(result)


def sum(a, b):
    return  a + b

def minus(a, b):
    return  a - b

caculate(3, 1, minus)

3 返回函数

def getFunc(flag):
    def sum(a, b, c):
        return a + b + c
    def minus(a, b, c):
        return a - b - c

    # 根据不同的flag值, 来返回不同的操作函数
    if flag == "+":
        return sum
    elif flag == "-":
        return minus


result = getFunc("-")
print(result, type(result))

res = result(1, 3, 5)
print(res)

4 匿名函数

lst = [{"name": "kk", "age": 1}, {"name": "kk2", "age": 2}, {"name": "kk3", "age": 3}]

# 普通用法,定义一个函数
# def getKey(x):
#     return x["age"]
# result = sorted(lst, key=getKey)

# 使用匿名函数,这样可以 减少行数 及 函数更加模块化
result = sorted(l, key=lambda x: x["age"])
print(result)

5 闭包

5.1 概念

条件

5.2 常见格式

def test(x):
    a = 10
    def test2():
        print(a)
        print(x)
    return test2

newFunc = test()
newFunc()

5.3 常用场景

def line_config(content, length):

    def line():
        print("-"*(length // 2) + content + "-"*(length // 2))
    return line


line1 =  line_config("闭包", 40)

line1()
line1()
line1()
line1()

5.4 注意事项

def test():
    num = 10
    def test2():
        nonlocal num
        num = 666
        print(num)
    print(num)
    test2()
    print(num)

    return test2

result = test()
result() # 此时 result 是指 test2

>>>
# 带有 nonlocal 时,结果,外层变量被修改了
10
666
666

# 没有 nonlocal 时,结果,外层变量没有被修改
10
666
10
情况1
def test():
    a = 1
    def test2():
        print(a)
    a = 2

    return test2

newFunc = test()
newFunc() # 结果是 2

情况2.1
def test():
    funcs = []
    for i in range(1, 4):
        def test2():
            print(i)
        funcs.append(test2)
    return funcs

newFuncs = test()

print(newFuncs)

newFuncs[0]()
newFuncs[1]()
newFuncs[2]()
结果是 >>>
3
3
3

情况2.2
def test():
    funcs = []
    for i in range(1, 4):
        def test2(num):
            def inner():
                print(num)
            return inner
        funcs.append(test2(i))
    return funcs

newFuncs = test()

print(newFuncs)

newFuncs[0]()
newFuncs[1]()
newFuncs[2]()
结果是 >>>
1
2
3
上一篇 下一篇

猜你喜欢

热点阅读