簡體   English   中英

制作一個裝飾器,可以訪問在 python 中作為輸入的函數的參數

[英]making a decorator that can access the arguments of the function that is taking as input in python

所以,我想寫一個裝飾器,它接受一個函數,並根據該函數參數決定是否做某事。

這個想法是,使用這個裝飾器,函數支持這樣的輸入:

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

您可以在裝飾器函數中使用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

這就是我到現在為止的想法:

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

更清楚的問題:

我再舉一個例子,因為我知道這個問題不是最好的:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM