简体   繁体   English

如何使用Python在基本装饰器中传递带有参数的函数?

[英]How to pass a function with a argument in a basic decorator using Python?

I am reading about decorators and have learned quite a bit from Simeons blog I had success before when there was no arguments passed in the function like this: decorator(func). 我正在阅读有关装饰器的信息,并且从Simeons博客中学到了很多东西,而在这样的函数中没有传递任何参数之前,我就取得了成功:decorator(func)。 I think my issue is decorator(func(args)). 我认为我的问题是decorator(func(args))。 I think my issue is func(args) is executing and passing its return value to the decorator instead of the function itself. 我认为我的问题是func(args)正在执行并将其返回值传递给装饰器,而不是函数本身。 How can I pass a function & argument in a decorator (example B) and not use the @decorator_name 'decoration' style (example A). 如何在修饰器中传递函数和参数(示例B),而不使用@decorator_name的“装饰”样式(示例A)。

Edit: I would like example B to produce the same result as example 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

Example A: This works 示例A:可行

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

read(user_input)

Example B: This does not work 示例B:这不起作用

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

camel_case(read(user_input))

THe decorator takes a function: camel_case(read) . 装饰器具有一个功能: camel_case(read) If you're trying to apply camel_case to the read(user_input) function, try this: 如果您尝试将camel_case应用于read(user_input)函数,请尝试以下操作:

camel_case(read)(user_input)

camel_case(read) returns the decorated function, which you then call with (user_input) . camel_case(read)返回修饰后的函数,然后使用(user_input)进行调用。

Give the function to the decorator as an argument; 将函数作为参数提供给装饰器; the decorator returns a new function; 装饰器返回一个新函数; then call this returned function with user_input as an argument: 然后使用user_input作为参数调用此返回的函数:

camel_case(read)(user_input) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM