【问题标题】:making a decorator that can access the arguments of the function that is taking as input in python制作一个装饰器,可以访问在python中作为输入的函数的参数
【发布时间】:2021-10-01 09:14:07
【问题描述】:

所以,我想写一个装饰器,它接受一个函数,并根据该函数参数决定是否做某事。

这个想法是,有了这个装饰器,函数支持这样的输入:

myFunction("a", "b", "c")

还有这样的输入:

myFunction(["a", "b", "c"])


def accept_list_input(function):
   def wrapper(function):
      try:
         function()
      except typeError:
      # (function's argument that i don't know how to access)= function's argument that i don't know how to access[0]

   return wrapper


@accept_list_input
def myFunction(*arguments):
   #stuff

【问题讨论】:

  • 那么你到底不希望这个函数允许什么作为参数?
  • 我希望这个函数将列表对象和无限参数作为输入,用逗号分隔但不作为列表
  • 这毫无意义,您只是自相矛盾地说您希望它接受一个列表而不是参数作为一个列表。
  • 这里好像没有问题。您当前的方法不能按您希望的方式工作。你能提供一个输入和预期输出的例子吗?

标签: python function arguments decorator


【解决方案1】:

你可以在装饰器函数中使用myFunction(*args, **kwargs),然后这样写装饰器函数:def decorator(func, *args, **kwargs)

在你的情况下,它会类似于:

myFunction(["a", "b", "c"])


def accept_list_input(function):
   def wrapper(*args, **kwargs):
      try:
         function(*args, **kwargs)
      except typeError:
      # (function's argument that i don't know how to access)= function's argument that i don't know how to access[0]

   return wrapper


@accept_list_input
def myFunction():
   #stuff

【讨论】:

  • 所以,我现在注意到我的问题的格式非常糟糕,我是这个网站的新手......但是我必须在哪里写 *args 和 **kwargs
  • 我不明白我必须把 *args 和 **kwargs 放在哪里
  • 对不起,如果我继续评论,但我真的需要一个例子。
【解决方案2】:

更清晰的问题:

我会再举一个例子,因为我知道这个问题不是最好的:

def add_numbers(*integer_numbers):
    sum= 0
    for integer in integer_numbers:
        sum+= integer
    return sum

# this is not the real method i am struggling on in my project, it's an example
# the function above takes an input formatted like this:
# add_numbers(1, 2, 3, 4, 5)
# i want the function to support both add_numbers(1, 2, 3, 4, 5) and add_numbers([1, 2, 3, 4, 5])


def accept_list_input(a_function, *args):
    def wrapper(func, args):
        try:
            a_function(args)
        except TypeError:
            for argument in args:
                if type(argument)== tuple:
                    argument= argument[0]
                    break
            a_function(args)
    return wrapper(a_function, args)

【讨论】:

  • 问题是,我想知道如何在装饰器中访问函数的参数:我希望能够看到在装饰器中作为参数传递的函数中有什么类型的参数
【解决方案3】:

这是我到现在为止的想法:

def accept_list_input(func, *args, **kwargs):
  def wrapper(func):
    try:
      func(args)
    except TypeError:
      for arg in args:
        if type(arg)== tuple:
          arg= arg[0]
        func(arg)
  return wrapper

【讨论】:

  • 您不希望此函数作为参数的原因是什么?你需要在你的提问中更清楚
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 2014-03-27
  • 2011-09-22
  • 2019-06-14
相关资源
最近更新 更多