Python闭包&装饰器

Python闭包

  • 闭包是一种与class相似但是在资源使用上却相对小很多的一种数据结构,我始终认为class就是一种特殊的保存or描述一类事物的数据结构。
  • 闭包的结构一般如下:

def test_one(temp_x, temp_y):
    def test_circle(temp_z):
        return temp_x * temp_y * temp_z
    return test_circle


test_main = test_one(2,5)
print(test_main(5))
print(test_main(6))

运行结果为:

# 显然类似于实例化的方式将2,5的数据保存导入test_main中,后面不需要多次传入参数即可使用该参数。
50
60

Python装饰器

  • 由于编程中几乎所有时候都要遵守 开放封闭 原则,原因是程序之间的耦合性已然未知,很可能在已有的代码中修改造成调用该函数的部分无法使用。

  • 正是考虑到这种情况,开放封闭 原则几乎一种被坚持遵守,一般可以使用装饰器能达到所需要的目的,扩展而不在原函数上修改。

  • 装饰器

# 多个装饰器对应一个函数...
def add_qx(func):
    print("---外层add_qx---")
    def call_func(*args, **kwargs):
        print("---add_qx---")
        return func(*args, **kwargs)
    return call_func


def add_xx(func):
    print("---外层add_xx---")
    def call_func(*args, **kwargs):
        print("---add_xx---")
        return func(*args, **kwargs)
    return call_func


def add_new(func):
    print("---外层add_new---")
    def call_func(*args, **kwargs):
        print("---add_new---")
        return func(*args, **kwargs)
    return call_func


@add_qx
@add_xx
@add_new
def test_one():
    print("------test_one------")


test_one()
  • 执行结果为:
---外层add_new---
---外层add_xx---
---外层add_qx---
---add_qx---
---add_xx---
---add_new---
------test1------
  • 可以理解为外层逆序,内层是顺序的。

  • 更加清晰的举例.

def test_one(main_test):
    def test_one_cricle():
        return "test_one " + main_test() + " /test_one"
    return test_one_cricle

def test_two(main_test):
    def test_two_circle():
        return "test_two_circle " + main_test() + " test_two_circle"
    return test_two_circle



@test_one
@test_two
def main_test():
    return "我是主测试."

print(main_test())
print("this is a final")

# 运行结果为:
test_one test_two_circle 我是主测试. test_two_circle /test_one
this is a final
  • 装饰器-装饰类
# 示范如下:
class class_test(object):
    """docstring for class_test"""

    def __init__(self, arg):
        super(class_test, self).__init__()
        self.arg = arg

    def __call__(self):
        print("主类测试")
        return self.arg()


@class_test
def class_main():
    return "this is class_main"


print(class_main())

# 运行结果为:
主类测试
this is class_main

重要的闭包与装饰器的联合使用,在WSGI文章较多.

猜你喜欢

转载自blog.csdn.net/CS_GaoMing/article/details/85625695