繁体   English   中英

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

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

我正在阅读有关装饰器的信息,并且从Simeons博客中学到了很多东西,而在这样的函数中没有传递任何参数之前,我就取得了成功:decorator(func)。 我认为我的问题是decorator(func(args))。 我认为我的问题是func(args)正在执行并将其返回值传递给装饰器,而不是函数本身。 如何在修饰器中传递函数和参数(示例B),而不使用@decorator_name的“装饰”样式(示例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) 如果您尝试将camel_case应用于read(user_input)函数,请尝试以下操作:

camel_case(read)(user_input)

camel_case(read)返回修饰后的函数,然后使用(user_input)进行调用。

将函数作为参数提供给装饰器; 装饰器返回一个新函数; 然后使用user_input作为参数调用此返回的函数:

camel_case(read)(user_input) 

暂无
暂无

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

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