【问题标题】:How to pass a function with a argument in a basic decorator using Python?如何使用 Python 在基本装饰器中传递带有参数的函数?
【发布时间】:2017-01-19 08:14:26
【问题描述】:

我正在阅读有关装饰器的内容,并且从 Simeons blog 那里学到了很多东西,我之前在函数中没有传递参数时取得了成功:装饰器(func)。我认为我的问题是装饰器(func(args))。我认为我的问题是 func(args) 正在执行并将其返回值传递给装饰器而不是函数本身。如何在装饰器中传递函数和参数(示例 B)而不使用 @decorator_name 'decoration' 样式(示例 A)。

编辑:我希望示例 B 产生与示例 A 相同的结果。

user_input = input("Type what you want:  ")

def camel_case(func):
   def _decorator(arg):
      s = ""
      words = arg.split()
      word_count = len(words)
      for i in range(word_count):
         if i >0:
            s += words[i].title()
         else:
            s += words[i].lower()
      return func(s)
   return _decorator

示例 A:可行

@camel_case
def read(text):
   print("\n" + text" )

read(user_input)

示例 B:这不起作用

def read(text):
   print("\n" + text" )

camel_case(read(user_input))

【问题讨论】:

  • 你想达到什么目的?
  • 你应该怎么做:camel_case(read)(user_input)
  • 刚刚编辑了问题。我希望示例 B 产生与示例 A 相同的结果。

标签: python python-decorators


【解决方案1】:

将函数作为参数传递给装饰器;装饰器返回一个新函数;然后用user_input 作为参数调用这个返回函数:

camel_case(read)(user_input) 

【讨论】:

    【解决方案2】:

    装饰器接受一个函数:camel_case(read)。如果您尝试将camel_case 应用于read(user_input) 函数,请尝试以下操作:

    camel_case(read)(user_input)
    

    camel_case(read) 返回修饰函数,然后您可以使用 (user_input) 调用该函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-21
      • 2021-07-27
      • 2020-03-22
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 2015-10-19
      相关资源
      最近更新 更多