python中的装饰器

    
def make_bold(func):
    def wrapper():
        return "<b>%s</b>" % func()
    return wrapper
@make_bold
def get_content():
    return "Hello World"
print(get_content())//输出为:<b>Hello World</b>

    添加@make_bold注释的get_content()的定义等价于:

get_content=make_bold(get_content)
实现带参数的装饰器
def make_header(level):
    print("Create decorator")
    def decorator(func):
        print("Initialize")
        def wrapper():
            print("call")
            return "<h{0}>{1}</h{0}>".format(level,func())
        return wrapper
    return decorator
@make_header(2)
def get_content():
    return "博主是个帅哥"
print(get_content())

输出为:

Create decorator
Initialize
call
<h2>博主是个帅哥</h2>

其实,带注释@make_header(2)的get_content()函数的定义,等价于

d=make_header(2)
get_content=d(get_content)
装饰有参数的函数

这个其实很简单

def make_bold(func):
    def wrapper(name):
        return "<b>%s</b>" % func(name)
    return wrapper
@make_bold
def get_content(name):
    return "Hello Mr."+name
print(get_content("博主"))

添加@make_bold注释的get_content()的定义等价于:

get_content=make_bold(get_content)
因为make_bold的返回值wrapper函数代表的是get_content,所以装饰带有参数的的函数,这个参数应该设置在wrapper函数上。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
装饰器Python一种用于修改函数或类的行为的语法结构。它们允许在不修改原始代码的情况下,通过添加额外的功能来装饰函数或类。 装饰器实际上是一个函数,它接受一个函数作为输入,并返回一个新的函数作为输出。这个新的函数通常会在调用原始函数之前或之后执行一些额外的代码。 下面是一个简单的装饰器示例: ```python def decorator_function(original_function): def wrapper_function(): # 在调用原始函数之前执行额外的操作 print("Before the original function is called") # 调用原始函数 original_function() # 在调用原始函数之后执行额外的操作 print("After the original function is called") return wrapper_function @decorator_function def say_hello(): print("Hello!") # 调用经过装饰器修饰过的函数 say_hello() ``` 在上述示例,我们定义了一个名为`decorator_function`的装饰器函数。该装饰器接受一个名为`original_function`的函数作为参数,并返回一个新的函数`wrapper_function`。`wrapper_function`在调用原始函数之前和之后,分别打印了一些额外的信息。 通过在`say_hello`函数定义之前加上`@decorator_function`,我们将`say_hello`函数传递给了装饰器,并将装饰器返回的函数赋值给了`say_hello`。这样,当我们调用`say_hello`函数时,实际上是在调用经过装饰器修饰过的函数`wrapper_function`。 装饰器提供了一种灵活且可重复使用的方式来扩展函数的功能,比如添加日志记录、性能计时、输入验证等。在Python,还有一种更简洁的语法糖形式来使用装饰器,即使用`@`符号将装饰器应用到函数上,如上述示例的`@decorator_function`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值