poorX

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
闭包

如果在一个函数内部,嵌套了函数,同时这个内部函数对(非全局作用域)外部作用域的变量进行引用,并且该函数可以在其定义环境外被执行,那么这个内部函数称为闭包。闭包每次运行是能记住引用的外部作用域的变量的值。

案例1
def outer():
    a = 2
    def inner(x):
        return x * a
    return inner

# 这里注意是 o = outer()
# 不是 o = outer(这样 o 是 outer 函数的引用)
# 而实际上 outer() 内部因为存在闭包
# 所以 o = outer(),o 实际上是 inner 函数的引用
o = outer()
print o(5)  # 输出 10
案例2
def outer(func):
    a = 2
    def inner(x):
        if x > 0:
            return func(x)
        return False
    return inner

@outer
def check(num):
    return "正常", num

# 不使用装饰器
o = outer(check)
print o(100)

# 使用装饰器
print check(100)

# 装饰器函数的入参就是装饰器所修饰的函数的引用
# 即装饰器函数内部的闭包
# 注意和案例1的区别:
# 1. 装饰器函数的入餐是修饰的函数
# 2. 被修饰的函数入参就是装饰器函数闭包的入参
# 3. 闭包内部如果不调用被修饰函数则这个装饰器没有意义
案例3
def outer(func):
    a = 2

    def inner(**kwargs):
        print(kwargs, kwargs['x'])
        if kwargs['x'] > 0:
            return func(**kwargs)
        return False

    return inner


@outer
def check(**kwargs):
    return "正常", kwargs['x']

# 不使用装饰器
o = outer(check)
print o(x=100)

# 使用装饰器
print check(x=100)
装饰器

闭包就是装饰器的实现,所以适合使用闭包的场景例如多个抽象实现可单独拆分,抽象内容相对独立

import time

# 注意
# 1 innerDecorator里面返回的函数要带括号
# 2 decorator返回的函数不带括号
def decorator(fun):
    def innerDecorator(arg):
        print time.time(), arg
        return fun(arg)
    return innerDecorator

@decorator
def fun1(arg):
    print 1
    return 1

@decorator
def fun2(arg):
    print 2
    return 2

if __name__ == '__main__':
    a = fun1(100)
    b = fun2(200)
单例开发

https://www.cnblogs.com/huchong/p/8244279.html

new
class Person(object):
  
    def __init__(self, name, age):
        self.name = name
        self.age = age
     
    def __new__(cls, name, age):
        if 0 < age < 150:
            return object.__new__(cls)
            # return super(Person, cls).__new__(cls)
        else:
            return None
  
    def __str__(self):
        return '{0}({1})'.format(self.__class__.__name__, self.__dict__)
  

print(Person('Tom', 10))
print(Person('Mike', 200))

# 结果

Person({'age': 10, 'name': 'Tom'})
None
cls

https://www.zhihu.com/question/49660420?sort=created

深拷贝 浅拷贝

https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html

适用场景?

posted on 2022-04-23 22:40  poorX  阅读(35)  评论(0编辑  收藏  举报