def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makebold @makeitalic def hello(): return "hello habr" print hello() ## <b><i>hello habr</i></b>
def shout(word=""): return word.capitalize()+"!" print shout() # : '!' # - , , # scream = shout # , : "shout", # "scream". , # "shout" "scream": print scream() # : '!' # , , "shout", # "scream" del shout try: print shout() except NameError, e: print e #: "name 'shout' is not defined" print scream() # : '!'
def talk(): # "talk" ... def whisper(word=""): return word.lower()+"..."; # ... ! print whisper() # , "talk", # "whisper". talk() # : "..." # "talk" "whisper": try: print whisper() except NameError, e: print e # : "name 'whisper' is not defined"
def getTalk(type="shout"): # def shout(word=""): return word.capitalize()+"!" def whisper(word="") : return word.lower()+"..."; # if type == "shout": # , "()", , # return shout else: return whisper # ? # talk = getTalk() # , "talk" - "function": print talk # : <function shout at 0xb7ea817c> # , , " ": print talk() # - : print getTalk("whisper")() # : ...
def doSomethingBefore(func): print " - , , " print func() doSomethingBefore(scream) #: # - , , # !
# - , def my_shiny_new_decorator(a_function_to_decorate): # -"". # ( ?..) , # . def the_wrapper_around_the_original_function(): # , # print " - , " # a_function_to_decorate() # , # print " - , " # "a_function_to_decorate" # , -, # , , . # ! return the_wrapper_around_the_original_function # , , . def a_stand_alone_function(): print " , ?.." a_stand_alone_function() # : , ?.. # , , , # , , # , , : a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function) a_stand_alone_function_decorated() #: # - , # , ?.. # - ,
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function) a_stand_alone_function() #: # - , # , ?.. # - ,
@my_shiny_new_decorator def another_stand_alone_function(): print " " another_stand_alone_function() #: # - , # # - ,
another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)
def bread(func): def wrapper(): print "</------\>" func() print "<\______/>" return wrapper def ingredients(func): def wrapper(): print "##" func() print "~~" return wrapper def sandwich(food="----"): print food sandwich() #: ---- sandwich = bread(ingredients(sandwich)) sandwich() #: # </------\> # ## # ---- # ~~ # <\______/>
@bread @ingredients def sandwich(food="----"): print food sandwich() #: # </------\> # ## # ---- # ~~ # <\______/>
@ingredients @bread def sandwich(food="----"): print food sandwich() #: # ## # </------\> # ---- # <\______/> # ~~
Source: https://habr.com/ru/post/141411/
All Articles