python_函数式编程

函数式编程是一种编程范式 (而面向过程编程和面向对象编程也都是编程范式)。在面向过程编程中,我们见到过函数(function);在面向对象编程中,我们见过对象(object)。函数和对象的根本目的是以某种逻辑方式组织代码,并提高代码的可重复使用性(reusability)。闭包也是一种组织代码的结构,它同样提高了代码的可重复使用性。 

闭包,这个东东有点像OC的block,封装的一个函数。,表现形式

def outer(x):
    def inner(y):
        return x+y
    return inner

result = outer(2)(3)
print('result' ,result)
打印:
result 5

使用闭包需要注意到遏地方

1.闭包无法修改外部函数的局部变量

def outer():
    c = 0
    print('out c1 ', c)
    def inner():
        c = 5
        print('inner c', c)
    inner()
    print('out c2', c)

outer()
 打印:
out c1  0
inner c 5
out c2 0

2.闭包无法直接访问外部函数的局部变量

装饰器:代码运行期间动态增加功能的方式,称之为“装饰器”。OC的runtime?

特点:1.参数是一个函数   2.返回值是一个函数

表现形式 - 及调用

#装饰器
def my_decorator(func):
    def wraper(*args, **kwargs):
        print('hello world')
        func(*args, ** kwargs)

    return wraper

@my_decorator
def run():
    print('run')

run()
打印:
hello world
run

装饰器如果不加限制,就会偷换调用者的方法名,这是很不安全的操作,如下

#装饰器
def my_decorator(func):
    def wraper(*args, **kwargs):
        print('hello world')
        func(*args, ** kwargs)

    return wraper

@my_decorator
def run():
    print('run')

func_name = run.__name__
run()
print('吊梁换柱后的函数', func_name)
打印:
hello world
run
吊梁换柱后的函数 wraper

需要导入个框架限制

from functools import wraps

并在内部函数定义前加上@wraps(函数名),这样就好了。如下

#装饰器
def my_decorator(func):
    @wraps(func)
    def wraper(*args, **kwargs):
        print('hello world')
        func(*args, ** kwargs)

    return wraper

@my_decorator
def run():
    print('run')

func_name = run.__name__
run()
print('吊梁换柱后的函数', func_name)
打印:
hello world
run
吊梁换柱后的函数 run

猜你喜欢

转载自www.cnblogs.com/shaoqizhi/p/9429762.html