可以将函数参数传递给装饰器吗?

huangapple go评论64阅读模式
英文:

Is it possible to pass a function argument into a decorator?

问题

Here is the translated code portion:

def my_decorator(func):

    def inner():
        """do stuff with arg"""
        func()

        return func

    return inner

@my_decorator
def my_func(arg):
    pass

If you have any further questions or need additional translations, please let me know.

英文:
def my_decorator(func):

    def inner():
        """do stuff with arg"""
        func()

        return func

    return inner

@my_decorator
def my_func(arg):
    pass

I wish to make the argument passed to the function my_function() to be passed to the decorator my_decorator(). I know it is possible to pass a variable to the decorator by putting it in a call like this: @my_decorator("arg"), but I am using the pycord library, which passes arguments directly to the function.

Is there any way to do it in Python, or will I have to find another way?

I could put this code in the function itself, but if the code is expanded later, it could cause problems, and it's way easier to maintain and update a single decorator/wrapper than change multiple places in code.

答案1

得分: 3

是的,您的 def inner(): 应该改为 def inner(arg):;毕竟,您从装饰器返回的函数有效地替换了原始函数。以下是代码的翻译部分:

def my_decorator(func):
    def inner(arg):
        print(f"将 {arg} 增加 1 后再传递给 func 前的操作!")
        return func(arg + 1)
    return inner

@my_decorator
def my_func(arg):
    print(f"my_func: {arg}")

my_func(9)

输出结果为:

将 9 增加 1 后再传递给 func 前的操作!
my_func: 10
英文:

Yes – your def inner(): should be def inner(arg):; after all, the function you return from the decorator effectively replaces the original function.

def my_decorator(func):
    def inner(arg):
        print(f"Going to increase {arg} by 1 before passing it to func!")
        return func(arg + 1)
    return inner

@my_decorator
def my_func(arg):
    print(f"my_func: {arg}")

my_func(9)

prints out

Going to increase 9 by 1 before passing it to func!
my_func: 10

答案2

得分: 0

是的,这是可能的,可以使用 *args**kwargs 来实现。

def my_decorator(func):
    def inner(*args, **kwargs):
        """处理参数的操作"""
        func(*args, **kwargs)

    return inner


@my_decorator
def my_func(arg):
    pass

请注意,我已经将HTML实体编码 " 替换为正常的双引号。

英文:

Yes, that is possible and could be achieved using *args amd **kwargs

def my_decorator(func):
    def inner(*args, **kwargs):
        """do stuff with arg"""
        func(*args, **kwargs)

        return func

    return inner


@my_decorator
def my_func(arg):
    pass

huangapple
  • 本文由 发表于 2023年5月21日 23:20:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76300612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定