Code: Select all
def hello(name): # generate "Hello, <name>"
return "Hello, "+name
def decorate(func): # decorator
def howru(name): # add ", how are you?"
return func(name)+", how are you?"
return howru
combined = decorate(hello) # new combined function to generate "Hello, <name>, how are you?"
print combined("John") # output: "Hello, John, how are you?"
Можно, конечно, добавить функцию, которая ничего не делает
Code: Select all
def pass_thru(arg):
return arg
Code: Select all
just_howru = decorate(pass_thru)
print just_howru("John") # output "John, how are you?"
PS Можно совсем обойтись без декораторов, но тогда нельзя создавать новые функции "на лету":
Code: Select all
def hello(name): # say "Hello, <name>"
return "Hello, "+name
def howru(name): # add ", how are you?"
return name+", how are you?"
print howru(hello("John")) # output "Hello, <name>, how are you?"
print howru("John") # output "John, how are you?"