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

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

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

问题

Here is the translated code portion:

  1. def my_decorator(func):
  2. def inner():
  3. """do stuff with arg"""
  4. func()
  5. return func
  6. return inner
  7. @my_decorator
  8. def my_func(arg):
  9. pass

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

英文:
  1. def my_decorator(func):
  2. def inner():
  3. """do stuff with arg"""
  4. func()
  5. return func
  6. return inner
  7. @my_decorator
  8. def my_func(arg):
  9. 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):;毕竟,您从装饰器返回的函数有效地替换了原始函数。以下是代码的翻译部分:

  1. def my_decorator(func):
  2. def inner(arg):
  3. print(f"将 {arg} 增加 1 后再传递给 func 前的操作!")
  4. return func(arg + 1)
  5. return inner
  6. @my_decorator
  7. def my_func(arg):
  8. print(f"my_func: {arg}")
  9. my_func(9)

输出结果为:

  1. 9 增加 1 后再传递给 func 前的操作!
  2. 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.

  1. def my_decorator(func):
  2. def inner(arg):
  3. print(f"Going to increase {arg} by 1 before passing it to func!")
  4. return func(arg + 1)
  5. return inner
  6. @my_decorator
  7. def my_func(arg):
  8. print(f"my_func: {arg}")
  9. my_func(9)

prints out

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

答案2

得分: 0

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

  1. def my_decorator(func):
  2. def inner(*args, **kwargs):
  3. """处理参数的操作"""
  4. func(*args, **kwargs)
  5. return inner
  6. @my_decorator
  7. def my_func(arg):
  8. pass

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

英文:

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

  1. def my_decorator(func):
  2. def inner(*args, **kwargs):
  3. """do stuff with arg"""
  4. func(*args, **kwargs)
  5. return func
  6. return inner
  7. @my_decorator
  8. def my_func(arg):
  9. 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:

确定