您的位置:首页 > 编程语言 > Python开发

python 装饰器实现

2017-09-21 14:03 218 查看
简单装饰器实现:

# -*- coding: utf-8 -*-
'''
装饰器的特点:对原函数是透明的

实现方式是: 高阶函数+ 嵌套函数
'''
from _ctypes_test import func

def decorator(func):
'''
定义装饰器 *args,**kwargs  这两个是为了接收不固定的参数
'''
def test(*args,**kwargs):
print("test 装饰器运行------>")
func(*args,**kwargs)
print("test 装饰器运行结束")

return test

'''
使用 @decorator 这种方式(@装饰器名字)来调用装饰器

'''
@decorator
def func_1():
print("func_1方法被调用")

@decorator
def func_2(name):
print("this is  func_2:",name)

func_1()
func_2("name")


被装饰的函数带有返回值:

'''
根据 type 运行指定的装饰器
'''

def decorator_name(decorator_type):
def switch(func):
def  wrapper(*args,**kwargs):
if decorator_type=="name":
print("name decorator is run ---->")
res = func(*args,**kwargs)  #接收被装饰函数的返回值
print("name decorator stop ------")
return res #返回
elif decorator_type=="fullName":
print("fullName decorator is run ---->")
res = func(*args,**kwargs)  #接收被装饰函数的返回值
print("fullName decorator stop ------")
return res #返回
return wrapper
return switch
@decorator_name(decorator_type="name")
def func_name(name):
print("my name is :",name)
return name

@decorator_name(decorator_type="fullName")
def func_fullName(name):
print("fullName is :",name)
return name

func_name("xiaoQang")
func_fullName("wangwang")


type
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: