python中类装饰器

类装饰器

  • 闭包:
  • 类装饰器

闭包:

1.函数嵌套定义
         外部函数
                   内部函数
                              内部函数
                                       …
2.内部函数使用外部函数作用域内的变量
3.外部函数要有返回值,返回内部函数名

def func_out(func):
    def func_in(*args,**kwargs):
        print("我是新增功能")
        return func(*args,**kwargs)
    return func_in

@func_out
#test = func_out(test)
def test():
    print("我是测试函数")

test()

执行结果

我是新增功能
我是测试函数

类装饰器

class Test():
    def __init__(self,func):
        self.func = func
        print("我是新增功能")
        self.func()
    #解决'Test' object is not callable
    def __call__(self, *args, **kwargs):
        pass
@Test
#test = Test(test)
def test():
    print("我是测试函数")
# TypeError: 'Test' object is not callable
# test()

执行结果

我是新增功能
我是测试函数
class Test(object):
    def __init__(self,func):
        print("--初始化--")
        print("func name is %s"%func.__name__)
        self.__func = func
    # 重写该方法后,对象可以直接进行调用
    def __call__(self):
        print("--装饰器中的功能--")
        self.__func()
# @Test 等价于  test = Test(test) 装饰器特性
@Test
def test():
    print('--test 函数---')
# 本身test指向函数test,但是装饰器将test指向了对象。
#  对象本身不可以被调用,但是重写__call__方法之后则会被调用
test()

执行结果

--初始化--
func name is test
--装饰器中的功能--
--test 函数---

你可能感兴趣的:(python)