簡體   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