Python decorator 拦截器

Posted 花生与浊酒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python decorator 拦截器相关的知识,希望对你有一定的参考价值。

例1 最简单

def get_text(name):
    return "hello, {0}".format(name)

def p_decorate(func):
    def func_wrapper(name):
        return "<p>{0}</p>".format(func(name))
    return func_wrapper

my_get_text = p_decorate(get_text)
print(my_get_text("zhangsan"))

 

例2 参数通用化

def p_decorate(func):
   def func_wrapper(*args, **kwargs):
       return "<p>{0}</p>".format(func(*args, **kwargs))
   return func_wrapper

class Person(object):
    def __init__(self):
        self.name = "Neng"
        self.family = "Xiong"

    @p_decorate
    def get_fullname(self):
        return self.name+" "+self.family

my_person = Person()
print(my_person.get_fullname())

 

例3  根据参数,实现动态拦截器

def tags(tag_name):
    def tags_decorator(func):
        def func_wrapper(*args, **kargs):
            return "<{0}>{1}</{0}>".format(tag_name, func(*args, **kargs))
        return func_wrapper
    return tags_decorator

@tags("div")
@tags("p")
@tags("strong")
def get_text(name):
    return "hello, "+name

print(get_text("zhangsan"))

 

以上是关于Python decorator 拦截器的主要内容,如果未能解决你的问题,请参考以下文章

python中的decorator的作用

python之装饰器(decorator)

15-python-decorators

python--decorator装饰器

python decorator的本质

Python – 装饰器(Decorator)