简体   繁体   English

Python装饰器跳过装饰函数的代码

[英]Python decorator skips the code of the decorated function

This code skips the code in the number function: 此代码跳过number函数中的代码:

def some_decorator(x):
     def wrapper(x):
         return x+1
     return wrapper

@some_decorator
def number(x):
    x = x + 100
    return x

Output: 输出:

>>> number(3)
4

I am trying to make the output of number(3) to be 104, what is wrong with the code? 我正在尝试将number(3)的输出设为104,代码有什么问题?

Decorators pass the function as an argument to the decorator. 装饰器将函数作为参数传递给装饰器。 It's your job to call the function if you want it to execute: 如果要执行该函数,则是您的工作:

def some_decorator(fn):
    def wrapper(x):
         return fn(x) + 1 # call the function and add 1 
    return wrapper

@some_decorator
def n(x):
    x = x + 100
    return x

n(3) # 104

As a side note, it's often useful to use functools.wraps to make the wrapped function behave as expected: 附带说明一下,通常可以使用functools.wraps使包装的函数按预期运行:

from functools import wraps

def some_decorator(fn):
    @wraps(fn)
    def wrapper(x):
         return fn(x) + 1
    return wrapper

@some_decorator
def n(x):
    x = x + 100
    return x

print(n.__name__) # now prints `n` instead of `wrapper`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM