简体   繁体   中英

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). I think my issue is 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. How can I pass a function & argument in a decorator (example B) and not use the @decorator_name 'decoration' style (example A).

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

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

read(user_input)

Example B: This does not work

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

camel_case(read(user_input))

THe decorator takes a function: 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) returns the decorated function, which you then call with (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:

camel_case(read)(user_input) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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