ක්‍රියාකාරී සැරසිලි කරුවන්ගේ දාමයක් සාදා ගන්නේ කෙසේද?


2762

පයිතන් හි සැරසිලි කරුවන් දෙදෙනෙකු සාදා ගන්නේ කෙසේද?

@makebold
@makeitalic
def say():
   return "Hello"

... නැවත පැමිණිය යුත්තේ:

"<b><i>Hello</i></b>"

මම HTMLසැබෑ යෙදුමකින් මෙය කිරීමට උත්සාහ නොකරමි - සැරසිලි කරුවන් සහ සැරසිලි දම්වැල් ක්‍රියා කරන ආකාරය තේරුම් ගැනීමට උත්සාහ කරමි.

Answers:


2932

පරීක්ෂා කරන්න ලේඛගතකිරීම සැරසිළි වැඩ ආකාරය. මෙන්න ඔබ ඉල්ලූ දේ:

from functools import wraps

def makebold(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<b>" + fn(*args, **kwargs) + "</b>"
    return wrapped

def makeitalic(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<i>" + fn(*args, **kwargs) + "</i>"
    return wrapped

@makebold
@makeitalic
def hello():
    return "hello world"

@makebold
@makeitalic
def log(s):
    return s

print hello()        # returns "<b><i>hello world</i></b>"
print hello.__name__ # with functools.wraps() this returns "hello"
print log('hello')   # returns "<b><i>hello</i></b>"

262
Functools.wraps හෝ වඩා හොඳ, PyPI වෙතින් සැරසිලි මොඩියුලය භාවිතා කිරීම ගැන සලකා බලන්න : ඒවා සමහර වැදගත් පාර-දත්ත ආරක්ෂා කරයි ( __name__සැරසිලි පැකේජය ගැන කථා කිරීම, ක්‍රියාකාරී අත්සන වැනි).
මාරියස් ගෙඩ්මිනාස්

31
*argsසහ **kwargsපිළිතුරට එකතු කළ යුතුය. අලංකාර කරන ලද ශ්‍රිතයට තර්ක තිබිය හැකි අතර, නිශ්චිතව දක්වා නොමැති නම් ඒවා නැති වී යයි.
බ්ලස්කි

3
මෙම පිළිතුරට stdlib භාවිතා කිරීමෙන් පමණක් විශාල වාසියක් ඇතත්, සැරසිලි තර්ක හෝ අලංකාර කරන ලද ක්‍රියාකාරී තර්ක නොමැති මෙම සරල උදාහරණය සඳහා ක්‍රියා කරයි , එයට ප්‍රධාන සීමාවන් 3 ක් ඇත: (1) විකල්ප සැරසිලි තර්ක සඳහා සරල සහායක් නොමැත (2) අත්සන-ආරක්ෂා (3) සිට නම් තර්කය උපුටා ගැනීම කිසිදු සරල ක්රමයක් *args, **kwargs. මෙම ගැටළු 3 එකවර විසඳීමට පහසු ක්‍රමයක් වන්නේ මෙහිdecopatch විස්තර කර ඇති ආකාරයට භාවිතා කිරීමයි . ලකුණු 2 සහ 3 විසඳීමට ඔබට දැනටමත් මාරියස් ගෙඩ්මිනාස් සඳහන් කළ පරිදි භාවිතා කළ හැකිය .decorator
ස්මාරි

4220

ඔබ දිගු පැහැදිලි කිරීම් වලට සම්බන්ධ නොවන්නේ නම්, පාවුලෝ බර්ගන්ටිනෝගේ පිළිතුර බලන්න .

සැරසිලි මූලික කරුණු

පයිතන්ගේ කාර්යයන් වස්තු වේ

සැරසිලි කරුවන් තේරුම් ගැනීමට, ඔබ මුලින් තේරුම් ගත යුත්තේ ශ්‍රිතයන් පයිතන්හි ඇති වස්තු බවයි. මෙය වැදගත් ප්‍රතිවිපාක ඇත. සරල උදාහරණයකින් එය බලමු:

def shout(word="yes"):
    return word.capitalize()+"!"

print(shout())
# outputs : 'Yes!'

# As an object, you can assign the function to a variable like any other object 
scream = shout

# Notice we don't use parentheses: we are not calling the function,
# we are putting the function "shout" into the variable "scream".
# It means you can then call "shout" from "scream":

print(scream())
# outputs : 'Yes!'

# More than that, it means you can remove the old name 'shout',
# and the function will still be accessible from 'scream'

del shout
try:
    print(shout())
except NameError as e:
    print(e)
    #outputs: "name 'shout' is not defined"

print(scream())
# outputs: 'Yes!'

මෙය මතකයේ තබා ගන්න. අපි ඉක්මනින්ම ඒ වෙත රවුම් කරන්නෙමු.

පයිතන් ශ්‍රිතවල තවත් සිත්ගන්නාසුලු ගුණාංගයක් නම් ඒවා වෙනත් ශ්‍රිතයක් තුළ අර්ථ දැක්විය හැකිය!

def talk():

    # You can define a function on the fly in "talk" ...
    def whisper(word="yes"):
        return word.lower()+"..."

    # ... and use it right away!
    print(whisper())

# You call "talk", that defines "whisper" EVERY TIME you call it, then
# "whisper" is called in "talk". 
talk()
# outputs: 
# "yes..."

# But "whisper" DOES NOT EXIST outside "talk":

try:
    print(whisper())
except NameError as e:
    print(e)
    #outputs : "name 'whisper' is not defined"*
    #Python's functions are objects

කාර්යයන් යොමු කිරීම

හරි, තාම මෙතනද? දැන් විනෝදජනක කොටස ...

ශ්‍රිත වස්තු බව ඔබ දැක ඇත. එබැවින්, කාර්යයන්:

  • විචල්යයකට පැවරිය හැකිය
  • වෙනත් ශ්‍රිතයකින් අර්ථ දැක්විය හැක

එයින් අදහස් වන්නේ ශ්‍රිතයකට returnවෙනත් ශ්‍රිතයක් කළ හැකි බවයි.

def getTalk(kind="shout"):

    # We define functions on the fly
    def shout(word="yes"):
        return word.capitalize()+"!"

    def whisper(word="yes") :
        return word.lower()+"...";

    # Then we return one of them
    if kind == "shout":
        # We don't use "()", we are not calling the function,
        # we are returning the function object
        return shout  
    else:
        return whisper

# How do you use this strange beast?

# Get the function and assign it to a variable
talk = getTalk()      

# You can see that "talk" is here a function object:
print(talk)
#outputs : <function shout at 0xb7ea817c>

# The object is the one returned by the function:
print(talk())
#outputs : Yes!

# And you can even use it directly if you feel wild:
print(getTalk("whisper")())
#outputs : yes...

තවත් බොහෝ දේ ඇත!

ඔබට returnශ්‍රිතයක් කළ හැකි නම්, ඔබට එය පරාමිතියක් ලෙස සම්මත කළ හැකිය:

def doSomethingBefore(func): 
    print("I do something before then I call the function you gave me")
    print(func())

doSomethingBefore(scream)
#outputs: 
#I do something before then I call the function you gave me
#Yes!

හොඳයි, සැරසිලි කරුවන් තේරුම් ගැනීමට අවශ්‍ය සියල්ල ඔබ සතුව ඇත. සැරසිලි කරන්නන් “එතීම” බව ඔබට පෙනේ, එයින් අදහස් කරන්නේ ඔවුන් විසින් ශ්‍රිතය වෙනස් නොකර ඔවුන් අලංකාර කරන කාර්යයට පෙර සහ පසු කේත ක්‍රියාත්මක කිරීමට ඔවුන් ඔබට ඉඩ දෙන බවයි.

අත්කම් සැරසිලි කරන්නන්

ඔබ එය අතින් කරන්නේ කෙසේද:

# A decorator is a function that expects ANOTHER function as parameter
def my_shiny_new_decorator(a_function_to_decorate):

    # Inside, the decorator defines a function on the fly: the wrapper.
    # This function is going to be wrapped around the original function
    # so it can execute code before and after it.
    def the_wrapper_around_the_original_function():

        # Put here the code you want to be executed BEFORE the original function is called
        print("Before the function runs")

        # Call the function here (using parentheses)
        a_function_to_decorate()

        # Put here the code you want to be executed AFTER the original function is called
        print("After the function runs")

    # At this point, "a_function_to_decorate" HAS NEVER BEEN EXECUTED.
    # We return the wrapper function we have just created.
    # The wrapper contains the function and the code to execute before and after. It’s ready to use!
    return the_wrapper_around_the_original_function

# Now imagine you create a function you don't want to ever touch again.
def a_stand_alone_function():
    print("I am a stand alone function, don't you dare modify me")

a_stand_alone_function() 
#outputs: I am a stand alone function, don't you dare modify me

# Well, you can decorate it to extend its behavior.
# Just pass it to the decorator, it will wrap it dynamically in 
# any code you want and return you a new function ready to be used:

a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs

දැන්, ඔබ සමහර විට ඔබ කතා හැම වෙලාවෙම අවශ්ය a_stand_alone_function, a_stand_alone_function_decoratedඒ වෙනුවට ලෙස හැඳින්වේ. එය පහසුය, නැවත a_stand_alone_functionලබා දුන් ශ්‍රිතය සමඟ නැවත ලියන්න my_shiny_new_decorator:

a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs

# That’s EXACTLY what decorators do!

සැරසිලි කරුවන් අවලංගු කරන ලදි

පෙර උදාහරණය, ​​සැරසිලි සින්ටැක්ස් භාවිතා කිරීම:

@my_shiny_new_decorator
def another_stand_alone_function():
    print("Leave me alone")

another_stand_alone_function()  
#outputs:  
#Before the function runs
#Leave me alone
#After the function runs

ඔව්, එච්චරයි, එය එතරම්ම සරලයි. @decoratorකෙටිමඟක් පමණි:

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("#tomatoes#")
        func()
        print("~salad~")
    return wrapper

def sandwich(food="--ham--"):
    print(food)

sandwich()
#outputs: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

පයිතන් සැරසිලි සින්ටැක්ස් භාවිතා කිරීම:

@bread
@ingredients
def sandwich(food="--ham--"):
    print(food)

sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

ඔබ සැරසිලි කරුවන් සැකසූ අනුපිළිවෙල වැදගත්:

@ingredients
@bread
def strange_sandwich(food="--ham--"):
    print(food)

strange_sandwich()
#outputs:
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~

දැන්: ප්‍රශ්නයට පිළිතුරු දීමට ...

නිගමනයක් ලෙස, ප්‍රශ්නයට පිළිතුරු දිය හැකි ආකාරය ඔබට පහසුවෙන් දැක ගත හැකිය:

# The decorator to make it bold
def makebold(fn):
    # The new function the decorator returns
    def wrapper():
        # Insertion of some code before and after
        return "<b>" + fn() + "</b>"
    return wrapper

# The decorator to make it italic
def makeitalic(fn):
    # The new function the decorator returns
    def wrapper():
        # Insertion of some code before and after
        return "<i>" + fn() + "</i>"
    return wrapper

@makebold
@makeitalic
def say():
    return "hello"

print(say())
#outputs: <b><i>hello</i></b>

# This is the exact equivalent to 
def say():
    return "hello"
say = makebold(makeitalic(say))

print(say())
#outputs: <b><i>hello</i></b>

ඔබට දැන් සතුටින් සිටිය හැකිය, නැතහොත් ඔබේ මොළය තව ටිකක් පුළුස්සා අලංකරණ ශිල්පීන්ගේ උසස් භාවිතයන් බලන්න.


සැරසිලි කරුවන් ඊළඟ මට්ටමට ගෙන යාම

අලංකාර කරන ලද කාර්යයට තර්ක ඉදිරිපත් කිරීම

# It’s not black magic, you just have to let the wrapper 
# pass the argument:

def a_decorator_passing_arguments(function_to_decorate):
    def a_wrapper_accepting_arguments(arg1, arg2):
        print("I got args! Look: {0}, {1}".format(arg1, arg2))
        function_to_decorate(arg1, arg2)
    return a_wrapper_accepting_arguments

# Since when you are calling the function returned by the decorator, you are
# calling the wrapper, passing arguments to the wrapper will let it pass them to 
# the decorated function

@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
    print("My name is {0} {1}".format(first_name, last_name))

print_full_name("Peter", "Venkman")
# outputs:
#I got args! Look: Peter Venkman
#My name is Peter Venkman

අලංකරණ ක්‍රම

පයිතන් පිළිබඳ එක් වැදගත් දෙයක් නම් ක්‍රම සහ කාර්යයන් සැබවින්ම එක හා සමාන වීමයි. එකම වෙනස වන්නේ ක්‍රම මඟින් ඔවුන්ගේ පළමු තර්කය වත්මන් වස්තුව ( self) වෙත යොමු කිරීමක් යැයි අපේක්ෂා කිරීමයි .

ඒ කියන්නේ ඔබට ක්‍රම සඳහා සැරසිලි කරුවෙකු එකම ආකාරයකින් සාදා ගත හැකිය! selfසැලකිල්ලට ගැනීමට මතක තබා ගන්න :

def method_friendly_decorator(method_to_decorate):
    def wrapper(self, lie):
        lie = lie - 3 # very friendly, decrease age even more :-)
        return method_to_decorate(self, lie)
    return wrapper


class Lucy(object):

    def __init__(self):
        self.age = 32

    @method_friendly_decorator
    def sayYourAge(self, lie):
        print("I am {0}, what did you think?".format(self.age + lie))

l = Lucy()
l.sayYourAge(-3)
#outputs: I am 26, what did you think?

ඔබ පොදු කාර්ය අලංකරණ ශිල්පියෙකු කරන්නේ නම් - ඔබ ඕනෑම කාර්යයකට හෝ ක්‍රමයකට අදාළ වනු ඇත, එහි තර්ක නොසලකා - ඉන්පසු භාවිතා කරන්න *args, **kwargs:

def a_decorator_passing_arbitrary_arguments(function_to_decorate):
    # The wrapper accepts any arguments
    def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
        print("Do I have args?:")
        print(args)
        print(kwargs)
        # Then you unpack the arguments, here *args, **kwargs
        # If you are not familiar with unpacking, check:
        # http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
        function_to_decorate(*args, **kwargs)
    return a_wrapper_accepting_arbitrary_arguments

@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
    print("Python is cool, no argument here.")

function_with_no_argument()
#outputs
#Do I have args?:
#()
#{}
#Python is cool, no argument here.

@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
    print(a, b, c)

function_with_arguments(1,2,3)
#outputs
#Do I have args?:
#(1, 2, 3)
#{}
#1 2 3 

@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus="Why not ?"):
    print("Do {0}, {1} and {2} like platypus? {3}".format(a, b, c, platypus))

function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!")
#outputs
#Do I have args ? :
#('Bill', 'Linus', 'Steve')
#{'platypus': 'Indeed!'}
#Do Bill, Linus and Steve like platypus? Indeed!

class Mary(object):

    def __init__(self):
        self.age = 31

    @a_decorator_passing_arbitrary_arguments
    def sayYourAge(self, lie=-3): # You can now add a default value
        print("I am {0}, what did you think?".format(self.age + lie))

m = Mary()
m.sayYourAge()
#outputs
# Do I have args?:
#(<__main__.Mary object at 0xb7d303ac>,)
#{}
#I am 28, what did you think?

සැරසිලි කරුවාට තර්ක ඉදිරිපත් කිරීම

නියමයි, දැන් ඔබ සැරසිලි කරුවාට තර්ක ඉදිරිපත් කිරීම ගැන කුමක් කියයිද?

සැරසිලි කරුවෙකු ශ්‍රිතයක් තර්කයක් ලෙස පිළිගත යුතු බැවින් මෙය තරමක් විකෘති විය හැකිය. එමනිසා, ඔබට සරසන ලද ශ්‍රිතයේ තර්ක කෙලින්ම සැරසිලි කරුවාට ලබා දිය නොහැක.

විසඳුම වෙත ඉක්මන් වීමට පෙර, අපි කුඩා මතක් කිරීමක් ලියමු:

# Decorators are ORDINARY functions
def my_decorator(func):
    print("I am an ordinary function")
    def wrapper():
        print("I am function returned by the decorator")
        func()
    return wrapper

# Therefore, you can call it without any "@"

def lazy_function():
    print("zzzzzzzz")

decorated_function = my_decorator(lazy_function)
#outputs: I am an ordinary function

# It outputs "I am an ordinary function", because that’s just what you do:
# calling a function. Nothing magic.

@my_decorator
def lazy_function():
    print("zzzzzzzz")

#outputs: I am an ordinary function

එය හරියටම සමාන ය. " my_decorator" යනුවෙන් හැඳින්වේ. එබැවින් ඔබ @my_decorator, පයිතන්ට කියන්නේ විචල්‍යය විසින් ලේබල් කරන ලද ශ්‍රිතය “" ”ලෙස හඳුන්වන my_decoratorලෙසයි.

මෙය වැදගත්! ඔබ ලබා දෙන ලේබලය decorator- වෙත සෘජුව එල්ල කළ හැකි හෝ නොහැකි .

අපි නපුර කරමු. ☺

def decorator_maker():

    print("I make decorators! I am executed only once: "
          "when you make me create a decorator.")

    def my_decorator(func):

        print("I am a decorator! I am executed only when you decorate a function.")

        def wrapped():
            print("I am the wrapper around the decorated function. "
                  "I am called when you call the decorated function. "
                  "As the wrapper, I return the RESULT of the decorated function.")
            return func()

        print("As the decorator, I return the wrapped function.")

        return wrapped

    print("As a decorator maker, I return a decorator")
    return my_decorator

# Let’s create a decorator. It’s just a new function after all.
new_decorator = decorator_maker()       
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator

# Then we decorate the function

def decorated_function():
    print("I am the decorated function.")

decorated_function = new_decorator(decorated_function)
#outputs:
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function

# Let’s call the function:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.

මෙහි පුදුමයක් නැත.

අපි හරියටම එකම දේ කරමු, නමුත් සියලු කරදරකාරී අතරමැදි විචල්‍යයන් මඟ හරින්න:

def decorated_function():
    print("I am the decorated function.")
decorated_function = decorator_maker()(decorated_function)
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.

# Finally:
decorated_function()    
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.

අපි එය තවත් කෙටි කරමු :

@decorator_maker()
def decorated_function():
    print("I am the decorated function.")
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.

#Eventually: 
decorated_function()    
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.

හේයි, ඔබ එය දුටුවාද? අපි @සින්ටැක්ස් සමඟ ක්‍රියාකාරී ඇමතුමක් භාවිතා කළෙමු ! :-)

එබැවින්, තර්ක සමඟ සැරසිලි කරුවන් වෙත ආපසු යන්න. මැස්සන් මත සැරසිලි කරුවා උත්පාදනය කිරීම සඳහා අපට ශ්‍රිත භාවිතා කළ හැකි නම්, අපට එම ශ්‍රිතයට තර්ක ඉදිරිපත් කළ හැකිය, නේද?

def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):

    print("I make decorators! And I accept arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))

    def my_decorator(func):
        # The ability to pass arguments here is a gift from closures.
        # If you are not comfortable with closures, you can assume it’s ok,
        # or read: /programming/13857/can-you-explain-closures-as-they-relate-to-python
        print("I am the decorator. Somehow you passed me arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))

        # Don't confuse decorator arguments and function arguments!
        def wrapped(function_arg1, function_arg2) :
            print("I am the wrapper around the decorated function.\n"
                  "I can access all the variables\n"
                  "\t- from the decorator: {0} {1}\n"
                  "\t- from the function call: {2} {3}\n"
                  "Then I can pass them to the decorated function"
                  .format(decorator_arg1, decorator_arg2,
                          function_arg1, function_arg2))
            return func(function_arg1, function_arg2)

        return wrapped

    return my_decorator

@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2):
    print("I am the decorated function and only knows about my arguments: {0}"
           " {1}".format(function_arg1, function_arg2))

decorated_function_with_arguments("Rajesh", "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Sheldon
#I am the decorator. Somehow you passed me arguments: Leonard Sheldon
#I am the wrapper around the decorated function. 
#I can access all the variables 
#   - from the decorator: Leonard Sheldon 
#   - from the function call: Rajesh Howard 
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments: Rajesh Howard

මෙන්න එයයි: තර්ක සහිත සැරසිලි කරුවෙක්. තර්ක විචල්ය ලෙස සැකසිය හැකිය:

c1 = "Penny"
c2 = "Leslie"

@decorator_maker_with_arguments("Leonard", c1)
def decorated_function_with_arguments(function_arg1, function_arg2):
    print("I am the decorated function and only knows about my arguments:"
           " {0} {1}".format(function_arg1, function_arg2))

decorated_function_with_arguments(c2, "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Penny
#I am the decorator. Somehow you passed me arguments: Leonard Penny
#I am the wrapper around the decorated function. 
#I can access all the variables 
#   - from the decorator: Leonard Penny 
#   - from the function call: Leslie Howard 
#Then I can pass them to the decorated function
#I am the decorated function and only know about my arguments: Leslie Howard

ඔබට පෙනෙන පරිදි, මෙම උපක්‍රමය භාවිතා කර ඕනෑම ශ්‍රිතයක් මෙන් සැරසිලි කරුවාට තර්ක ඉදිරිපත් කළ හැකිය. *args, **kwargsඔබට අවශ්‍ය නම් පවා භාවිතා කළ හැකිය . නමුත් මතක තබා ගන්න සැරසිලි කරුවන් කැඳවනු ලබන්නේ එක් වරක් පමණි . පයිතන් පිටපත ආනයනය කරන විට. ඔබට පසුව තර්ක ගතිකව සැකසිය නොහැක. ඔබ "ආනයන x" කරන විට, ශ්‍රිතය දැනටමත් සරසා ඇති බැවින් ඔබට කිසිවක් වෙනස් කළ නොහැක.


අපි පුහුණු වෙමු: සැරසිලි කරුවෙකු අලංකාර කිරීම

හරි, ප්‍රසාද දීමනාවක් ලෙස, ඕනෑම සැරසිලි කරුවෙකු සාමාන්‍යයෙන් ඕනෑම තර්කයක් පිළිගැනීමට මම ඔබට ස්නිපටයක් දෙන්නෙමි. සියල්ලට පසු, තර්ක පිළිගැනීම සඳහා, අපි වෙනත් ශ්‍රිතයක් භාවිතා කරමින් අපගේ සැරසිලි කරුවා නිර්මාණය කළෙමු.

අපි සැරසිලි කරුවා ඔතා.

ඔතා ඇති ශ්‍රිතය මෑතකදී අප දුටුවාද?

ඔහ්, සැරසිලි කරන්නන්!

අපි විනෝද වෙමු, සැරසිලි කරන්නන් සඳහා සැරසිලි කරුවෙකු ලියමු:

def decorator_with_args(decorator_to_enhance):
    """ 
    This function is supposed to be used as a decorator.
    It must decorate an other function, that is intended to be used as a decorator.
    Take a cup of coffee.
    It will allow any decorator to accept an arbitrary number of arguments,
    saving you the headache to remember how to do that every time.
    """

    # We use the same trick we did to pass arguments
    def decorator_maker(*args, **kwargs):

        # We create on the fly a decorator that accepts only a function
        # but keeps the passed arguments from the maker.
        def decorator_wrapper(func):

            # We return the result of the original decorator, which, after all, 
            # IS JUST AN ORDINARY FUNCTION (which returns a function).
            # Only pitfall: the decorator must have this specific signature or it won't work:
            return decorator_to_enhance(func, *args, **kwargs)

        return decorator_wrapper

    return decorator_maker

එය පහත පරිදි භාවිතා කළ හැකිය:

# You create the function you will use as a decorator. And stick a decorator on it :-)
# Don't forget, the signature is "decorator(func, *args, **kwargs)"
@decorator_with_args 
def decorated_decorator(func, *args, **kwargs): 
    def wrapper(function_arg1, function_arg2):
        print("Decorated with {0} {1}".format(args, kwargs))
        return func(function_arg1, function_arg2)
    return wrapper

# Then you decorate the functions you wish with your brand new decorated decorator.

@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
    print("Hello {0} {1}".format(function_arg1, function_arg2))

decorated_function("Universe and", "everything")
#outputs:
#Decorated with (42, 404, 1024) {}
#Hello Universe and everything

# Whoooot!

මම දන්නවා, ඔබට අවසන් වරට මෙම හැඟීම ඇති වූ විට, එය "පුනරාවර්තනය තේරුම් ගැනීමට පෙර, ඔබ මුලින්ම පුනරාවර්තනය තේරුම් ගත යුතුය" යනුවෙන් පිරිමි ළමයෙක් පැවසීමෙන් පසුවය. නමුත් දැන්, මෙය ප්‍රගුණ කිරීම ගැන ඔබට හොඳ හැඟීමක් නැද්ද?


හොඳම පිළිවෙත්: සැරසිලි කරන්නන්

  • සැරසිලි කරුවන් පයිතන් 2.4 හි හඳුන්වා දෙන ලදි, එබැවින් ඔබේ කේතය> = 2.4 මත ක්‍රියාත්මක වන බවට වග බලා ගන්න.
  • සැරසිලි කරන්නන් ක්‍රියාකාරී ඇමතුම මන්දගාමී කරයි. එය මතකයේ තබා ගන්න.
  • ඔබට ශ්‍රිතයක් අලංකාර කිරීම කළ නොහැක. (එහි සිටින ඉවත් කළ හැකි බව, සැරසිළි නිර්මාණය කිරීමට මාරාවේශයෙන්, නමුත් කිසිවෙක් ඔවුන් භාවිතා කරයි.) ඒ නිසා උත්සවයකට සැරසී ඇත වරක්, එය මනාව වෙනවා සියලු කේතය සඳහා .
  • සැරසිලි කරන්නන් කාර්යයන් ඔතා, ඒවා නිදොස් කිරීමට අපහසු වේ. (මෙය පයිතන්> = 2.5 වෙතින් වඩා හොඳ වේ; පහත බලන්න.)

මෙම functoolsමොඩියුලය Python 2.5 හදුන්වා දෙන ලදි. එයට ශ්‍රිතය ඇතුළත් වේfunctools.wraps()අලංකාර කරන ලද ශ්‍රිතයේ නම, මොඩියුලය සහ ලේඛනය එහි එතීමට පිටපත් .

(විනෝදජනක කාරණය: functools.wraps()සැරසිලි කරුවෙකි! ☺)

# For debugging, the stacktrace prints you the function __name__
def foo():
    print("foo")

print(foo.__name__)
#outputs: foo

# With a decorator, it gets messy    
def bar(func):
    def wrapper():
        print("bar")
        return func()
    return wrapper

@bar
def foo():
    print("foo")

print(foo.__name__)
#outputs: wrapper

# "functools" can help for that

import functools

def bar(func):
    # We say that "wrapper", is wrapping "func"
    # and the magic begins
    @functools.wraps(func)
    def wrapper():
        print("bar")
        return func()
    return wrapper

@bar
def foo():
    print("foo")

print(foo.__name__)
#outputs: foo

සැරසිලි කරන්නන් ප්‍රයෝජනවත් වන්නේ කෙසේද?

දැන් විශාල ප්‍රශ්නය: මට සැරසිලි කරන්නන් භාවිතා කළ හැක්කේ කුමක් සඳහාද?

සිසිල් හා බලවත් බවක් පෙනේ, නමුත් ප්‍රායෝගික උදාහරණයක් විශිෂ්ට වනු ඇත. හොඳයි, හැකියාවන් 1000 ක් ඇත. ක්ලැසික් භාවිතයන් යනු බාහිර ලිබ් එකකින් (ඔබට එය වෙනස් කළ නොහැක), හෝ නිදොස් කිරීම සඳහා (එය තාවකාලික බැවින් එය වෙනස් කිරීමට ඔබට අවශ්‍ය නැත).

ඩ්‍රයි ආකාරයෙන් කාර්යයන් කිහිපයක් දීර් extend කිරීමට ඔබට ඒවා භාවිතා කළ හැකිය:

def benchmark(func):
    """
    A decorator that prints the time a function takes
    to execute.
    """
    import time
    def wrapper(*args, **kwargs):
        t = time.clock()
        res = func(*args, **kwargs)
        print("{0} {1}".format(func.__name__, time.clock()-t))
        return res
    return wrapper


def logging(func):
    """
    A decorator that logs the activity of the script.
    (it actually just prints it, but it could be logging!)
    """
    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        print("{0} {1} {2}".format(func.__name__, args, kwargs))
        return res
    return wrapper


def counter(func):
    """
    A decorator that counts and prints the number of times a function has been executed
    """
    def wrapper(*args, **kwargs):
        wrapper.count = wrapper.count + 1
        res = func(*args, **kwargs)
        print("{0} has been used: {1}x".format(func.__name__, wrapper.count))
        return res
    wrapper.count = 0
    return wrapper

@counter
@benchmark
@logging
def reverse_string(string):
    return str(reversed(string))

print(reverse_string("Able was I ere I saw Elba"))
print(reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!"))

#outputs:
#reverse_string ('Able was I ere I saw Elba',) {}
#wrapper 0.0
#wrapper has been used: 1x 
#ablE was I ere I saw elbA
#reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {}
#wrapper 0.0
#wrapper has been used: 2x
#!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A

ඇත්ත වශයෙන්ම සැරසිලි කරුවන් සමඟ ඇති හොඳ දෙය නම් ඔබට නැවත ලිවීමකින් තොරව ඕනෑම දෙයක් මත එකවරම භාවිතා කළ හැකිය. ඩ්‍රයි, මම කිව්වා:

@counter
@benchmark
@logging
def get_random_futurama_quote():
    from urllib import urlopen
    result = urlopen("http://subfusion.net/cgi-bin/quote.pl?quote=futurama").read()
    try:
        value = result.split("<br><b><hr><br>")[1].split("<br><br><hr>")[0]
        return value.strip()
    except:
        return "No, I'm ... doesn't!"


print(get_random_futurama_quote())
print(get_random_futurama_quote())

#outputs:
#get_random_futurama_quote () {}
#wrapper 0.02
#wrapper has been used: 1x
#The laws of science be a harsh mistress.
#get_random_futurama_quote () {}
#wrapper 0.01
#wrapper has been used: 2x
#Curse you, merciful Poseidon!

Python මීට උදාහරණ ම සැරසිලි කිහිපයක් සපයයි: property, staticmethodආදිය,

  • හැඹිලි කළමනාකරණය කිරීමට සහ අවසර බැලීමට ජැන්ගෝ සැරසිලි කරුවන් භාවිතා කරයි.
  • ව්‍යාජ ඉන්ලයින් අසමමුහුර්ත ශ්‍රිත ඇමතුම් වලට ඇඹරී ඇත.

මෙය සැබවින්ම විශාල ක්‍රීඩා පිටියකි.


16
"ඔබට ශ්‍රිතයක් අලංකාර කිරීම කළ නොහැක." - සාමාන්‍යයෙන් සත්‍යයක් වුවද, __closure__මුල් අවිනිශ්චිත ශ්‍රිතය පිටතට ගැනීම සඳහා සැරසිලි කරුවෙකු (එනම් එහි ගුණාංගය හරහා ) ශ්‍රිත ප්‍රතිලාභයේ වසා දැමීමේ ඇතුළත ළඟා විය හැකිය . එක් පිළිතුරක් භාවිතය මෙම පිළිතුරෙහි ලේඛනගත කර ඇති අතර එමඟින් සීමිත අවස්ථාවන්හිදී සැරසිලි කරුවෙකුගේ ක්‍රියාකාරිත්වය පහළ මට්ටමින් එන්නත් කළ හැකි ආකාරය ආවරණය කරයි.
metatoaster

8
මෙය හොඳ පිළිතුරක් වන අතර, එය යම් ආකාරයකින් නොමඟ යවන සුළු යැයි මම සිතමි. පයිතන්ගේ @decoratorවාක්‍ය ඛණ්ඩය බොහෝ විට භාවිතා කරනුයේ ශ්‍රිතයක් එතීමේ වසා දැමීමක් සමඟ ප්‍රතිස්ථාපනය කිරීමට ය (පිළිතුර විස්තර කරන පරිදි). නමුත් එයට ශ්‍රිතය වෙනත් දෙයක් සමඟ ප්‍රතිස්ථාපනය කළ හැකිය. මෙම builtin property, classmethodහා staticmethodසැරසිලි උදාහරණයක් ලෙස, descriptor සමග කාර්යය වෙනුවට. සැරසිලි කරුවෙකුට යම් ආකාරයක ලේඛනයක ඒ පිළිබඳ සඳහනක් සුරැකීම, පසුව එය නවීකරණයකින් තොරව, කිසිදු ආවරණයක් නොමැතිව ආපසු එවීම වැනි ශ්‍රිතයක් සමඟ යමක් කළ හැකිය.
Blckknght

3
“ශ්‍රිත වස්තු” යන කාරණය පයිතන්හි සම්පූර්ණයෙන්ම සත්‍ය වන අතර එය නොමඟ යවන සුළුය. විචල්‍යයන් තුළ ශ්‍රිත ගබඩා කිරීම, ඒවා තර්ක ලෙස සම්මත කිරීම සහ ඒවා ප්‍රති results ල ලෙස ආපසු ලබා දීම යන සියල්ලම සැබවින්ම වස්තූන් නොවී කළ හැකි අතර පළමු පන්තියේ කාර්යයන් ඇති නමුත් විවිධ වස්තූන් නොමැත.
00dani

1
මේක එක එපික් උත්තරයක් ... ස්තූතියි ටොන් එකක්! කෙසේ වෙතත්, ශ්‍රිතයක් සඳහා පෙරනිමි තර්ක, සැරසිලි කරුවාගේ ආවරණයේ ඇති ආග්ස් / ක්වාර්ග් ලෙස නොපෙන්වන්නේ කෙසේද?
නාස්

"සැරසිලි කරන්නන් ප්‍රයෝජනවත් වන්නේ කෙසේද?" මන්ද යත්, මෙම පිළිතුරේ ඉහළට ඉහළට ඉහළට අනුචලනය කරන්න. කොටස එතරම්ම ප්‍රයෝජනවත් විය.
නූමනන්

145

විකල්පයක් ලෙස, ඔබට කර්මාන්තශාලා ශ්‍රිතයක් ලිවිය හැකි අතර එය සැරසිලි කරුවෙකු ආපසු ලබා දෙන අතර එය අලංකාර කරන ලද ශ්‍රිතයේ ප්‍රතිලාභ අගය කර්මාන්තශාලා ශ්‍රිතයට ලබා දුන් ටැගයකින් ඔතා ඇත. උදාහරණයක් වශයෙන්:

from functools import wraps

def wrap_in_tag(tag):
    def factory(func):
        @wraps(func)
        def decorator():
            return '<%(tag)s>%(rv)s</%(tag)s>' % (
                {'tag': tag, 'rv': func()})
        return decorator
    return factory

මෙය ඔබට ලිවීමට ඉඩ දෙයි:

@wrap_in_tag('b')
@wrap_in_tag('i')
def say():
    return 'hello'

හෝ

makebold = wrap_in_tag('b')
makeitalic = wrap_in_tag('i')

@makebold
@makeitalic
def say():
    return 'hello'

පුද්ගලිකව මම සැරසිලි කරුවා තරමක් වෙනස් ලෙස ලිවීමට ඉඩ තිබුණි:

from functools import wraps

def wrap_in_tag(tag):
    def factory(func):
        @wraps(func)
        def decorator(val):
            return func('<%(tag)s>%(val)s</%(tag)s>' %
                        {'tag': tag, 'val': val})
        return decorator
    return factory

එය ලැබෙනු ඇත:

@wrap_in_tag('b')
@wrap_in_tag('i')
def say(val):
    return val
say('hello')

සැරසිලි සින්ටැක්ස් කෙටිකාලීන ඉදිකිරීමක් අමතක නොකරන්න:

say = wrap_in_tag('b')(wrap_in_tag('i')(say)))

5
මගේ මතය අනුව, හැකි තරම් සැරසිලි කරුවන් එකකට වඩා වැළකී සිටීම හොඳය. මම කර්මාන්ත කාර්යය ලියන්නට සිදු වුණා නම් මම වගේ * kwargs එය සංග්රහයේ def wrap_in_tag(*kwargs)පසුව@wrap_in_tag('b','i')
guneysus

120

ගැටලුව විසඳන්නේ කෙසේදැයි අනෙක් පුද්ගලයින් දැනටමත් ඔබට පවසා ඇති බව පෙනේ. සැරසිලි කරන්නන් යනු කුමක්දැයි වටහා ගැනීමට මෙය ඔබට උපකාරී වනු ඇතැයි මම බලාපොරොත්තු වෙමි.

සැරසිලි කරන්නන් යනු සින්ටැක්ටිකල් සීනි පමණි.

මෙය

@decorator
def func():
    ...

දක්වා පුළුල් වේ

def func():
    ...
func = decorator(func)

3
මෙය එතරම් අලංකාර, සරල, තේරුම් ගැනීමට පහසුය. 10000 ක් ඔබ වෙනුවෙන්, සර් ඔක්හැම්.
eric

2
විශිෂ්ට හා සරල පිළිතුරකි. භාවිතා කරන විට @decorator()(ඒ වෙනුවට @decorator) එය සින්ටැක්ටික් සීනි බව එකතු කිරීමට කැමතියි func = decorator()(func). ඔබට "මැස්සන් මත" සැරසිලි කරුවන් උත්පාදනය කිරීමට අවශ්‍ය වූ විට මෙයද සාමාන්‍ය සිරිතකි
ඔමර් ඩගන්

64

ඇත්ත වශයෙන්ම ඔබට ලැම්බඩස් මෙන්ම සැරසිලි ශ්‍රිතයකින් ආපසු යා හැකිය:

def makebold(f): 
    return lambda: "<b>" + f() + "</b>"
def makeitalic(f): 
    return lambda: "<i>" + f() + "</i>"

@makebold
@makeitalic
def say():
    return "Hello"

print say()

12
තවත් එක් පියවරක්:makebold = lambda f : lambda "<b>" + f() + "</b>"
රොබී

13
@ රොබෝ: කෘතිමව නිවැරදි වීමට:makebold = lambda f: lambda: "<b>" + f() + "</b>"
මාර්ටිනෝ

11
අග පක්ෂ, නමුත් මම ඇත්තටම යෝජනා කරන්නේmakebold = lambda f: lambda *a, **k: "<b>" + f(*a, **k) + "</b>"
seequ

functools.wrapsඩොක්ස්ට්‍රිං / අත්සන / නම ඉවත නොදැමීම සඳහා මෙය අවශ්‍ය වේsay
එරික්

හොඳයි, වැදගත් වන්නේ එය ඔබේ පිළිතුරේ සඳහන් කර තිබේද යන්නයි. සහිත @wrapsමෙම පිටුවේ වෙන කොහේ හරි මම මුද්රණය විට මට උදව් කරන්න යන්නේ නැහැ help(say)සහ ලබා "උත්සවය සඳහා උදව් <ලැම්ඩා> ' වෙනුවට කාර්යය මතය" මත උදව් " .
එරික්

61

පයිතන් සැරසිලි කරන්නන් වෙනත් ශ්‍රිතයකට අමතර ක්‍රියාකාරීත්වයක් එක් කරයි

ඇල අකුරු සැරසිලි කරුවෙකු මෙන් විය හැකිය

def makeitalic(fn):
    def newFunc():
        return "<i>" + fn() + "</i>"
    return newFunc

ශ්‍රිතයක් තුළ ශ්‍රිතයක් අර්ථ දක්වා ඇති බව සලකන්න. එය මූලික වශයෙන් කරන්නේ අළුතින් අර්ථ දක්වා ඇති ශ්‍රිතයක් ප්‍රතිස්ථාපනය කිරීමයි. උදාහරණයක් ලෙස, මට මෙම පන්තිය ඇත

class foo:
    def bar(self):
        print "hi"
    def foobar(self):
        print "hi again"

දැන් කියන්න, මට අවශ්‍ය කාර්යයන් දෙකම "---" මුද්‍රණය කර පසුව ඒවා සිදු කිරීමට පෙරය. එක් එක් මුද්‍රණ ප්‍රකාශයට පෙර සහ පසු මට "---" මුද්‍රණයක් එක් කළ හැකිය. නමුත් මම නැවත නැවත කියවීමට අකමැති නිසා මම සැරසිලි කරුවෙකු සාදමි

def addDashes(fn): # notice it takes a function as an argument
    def newFunction(self): # define a new function
        print "---"
        fn(self) # call the original function
        print "---"
    return newFunction
    # Return the newly defined function - it will "replace" the original

දැන් මට මගේ පන්තිය වෙනස් කළ හැකිය

class foo:
    @addDashes
    def bar(self):
        print "hi"

    @addDashes
    def foobar(self):
        print "hi again"

අලංකරණ ශිල්පීන් පිළිබඳ වැඩි විස්තර සඳහා, http://www.ibm.com/developerworks/linux/library/l-cpdecor.html පරීක්ෂා කරන්න


@Rune Kaagaard විසින් යෝජිත ලැම්ඩා කාර්යයන් ලෙස අලංකාර ලෙස සටහන
නිවාරණ වැඩසටහන්

1
Ho ෆීනික්ස්: selfතර්කය අවශ්‍ය වන්නේ newFunction()අර්ථ දක්වා ඇත්තේ addDashes()නිශ්චිතවම සැලසුම් කර ඇත්තේ සාමාන්‍ය සැරසිලි කරුවෙකු නොව ක්‍රම සැරසිලි කරුවෙකු ලෙසය. මෙම selfතර්කය පන්ති උදාහරණයක් නියෝජනය නොවේ ඔවුන් එය භාවිතා යන්න පන්ති ක්රම සම්මත හෝ වේ - මැයෙන් කොටස බලන්න වියදමකින් ක්රම @ ඊ-satis පිළිතුරේ.
මාර්ටිනෝ

1
කරුණාකර ප්‍රතිදානය මුද්‍රණය කරන්න.
user1767754

අතුරුදහන්functools.wraps
එරික්

39

ඔබ විය හැකි සෘජුවම පහත සිතියම්ගත ඔබට අවශ්ය දේ කරන වෙනම සැරසිළි දෙකක් කරන්න. බහුවිධ තර්ක සහිත අලංකාර කරන ලද ශ්‍රිතයට සහය දක්වන ශ්‍රිතයේ *args, **kwargsප්‍රකාශනයේ භාවිතය සැලකිල්ලට ගන්න wrapped()(එය උදාහරණ say()ශ්‍රිතයට සැබවින්ම අවශ්‍ය නොවන නමුත් සාමාන්‍ය බව සඳහා ඇතුළත් කර ඇත).

ඒ හා සමාන හේතූන් මත, functools.wrapsසැරසිලි කරුවාගේ ඔතා ඇති ශ්‍රිතයේ මෙටා ගුණාංග අලංකාර කිරීම සඳහා යොදා ගනී. මෙය දෝෂ පණිවිඩ සහ කාවැද්දූ ශ්‍රිත ලියකියවිලි ( func.__doc__) වෙනුවට අලංකාර කරන ලද ශ්‍රිතයේ ඒවා වේ wrapped().

from functools import wraps

def makebold(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<b>" + fn(*args, **kwargs) + "</b>"
    return wrapped

def makeitalic(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<i>" + fn(*args, **kwargs) + "</i>"
    return wrapped

@makebold
@makeitalic
def say():
    return 'Hello'

print(say())  # -> <b><i>Hello</i></b>

පිරිපහදු

ඔබට පෙනෙන පරිදි මෙම සැරසිලි කරුවන් දෙදෙනා තුළ අනුපිටපත් කේත රාශියක් ඇත. මෙම සමානතාවය සැලකිල්ලට ගෙන, ඒ වෙනුවට ඇත්ත වශයෙන්ම සැරසිලි කර්මාන්ත ශාලාවක් වූ සාමාන්‍ය එකක් සෑදීම වඩා හොඳය - වෙනත් වචන වලින් කිවහොත්, වෙනත් සැරසිලි කරුවන් බවට පත් කරන සැරසිලි ශ්‍රිතයකි. එමගින් කේත පුනරාවර්තනය අඩු වනු ඇත - සහ DRY මූලධර්මය අනුගමනය කිරීමට ඉඩ දෙන්න .

def html_deco(tag):
    def decorator(fn):
        @wraps(fn)
        def wrapped(*args, **kwargs):
            return '<%s>' % tag + fn(*args, **kwargs) + '</%s>' % tag
        return wrapped
    return decorator

@html_deco('b')
@html_deco('i')
def greet(whom=''):
    return 'Hello' + (' ' + whom) if whom else ''

print(greet('world'))  # -> <b><i>Hello world</i></b>

කේතය වඩාත් කියවිය හැකි වන පරිදි, කර්මාන්තශාලාවෙන් ජනනය කරන ලද සැරසිලි කරුවන්ට වඩාත් විස්තරාත්මක නමක් ලබා දිය හැකිය:

makebold = html_deco('b')
makeitalic = html_deco('i')

@makebold
@makeitalic
def greet(whom=''):
    return 'Hello' + (' ' + whom) if whom else ''

print(greet('world'))  # -> <b><i>Hello world</i></b>

හෝ ඒවා මේ ආකාරයට ඒකාබද්ධ කරන්න:

makebolditalic = lambda fn: makebold(makeitalic(fn))

@makebolditalic
def greet(whom=''):
    return 'Hello' + (' ' + whom) if whom else ''

print(greet('world'))  # -> <b><i>Hello world</i></b>

කාර්යක්ෂමතාව

ඉහත උදාහරණ සියල්ලම ක්‍රියාත්මක වන අතර, ජනනය කරන ලද කේතයට එකවර විවිධ සැරසිලි කරුවන් යොදන විට බාහිර ක්‍රියාකාරී ඇමතුම් ස්වරූපයෙන් සාධාරණ පොදු කාර්ය ප්‍රමාණයක් ඇතුළත් වේ. නිශ්චිත භාවිතය මත පදනම්ව මෙය වැදගත් නොවනු ඇත (උදාහරණයක් ලෙස I / O- බැඳී තිබිය හැක).

අලංකාර කරන ලද ශ්‍රිතයේ වේගය වැදගත් නම්, තරමක් වෙනස් සැරසිලි කර්මාන්තශාලා ශ්‍රිතයක් ලිවීමෙන් උඩිස් එක අමතර ක්‍රියාකාරී ඇමතුමකට තබා ගත හැකි අතර එමඟින් සියලු ටැග් එකවර එකතු කිරීම ක්‍රියාත්මක කරයි, එමඟින් එකතු කළ ශ්‍රිත ඇමතුම් මඟහරවා කේත ජනනය කළ හැකිය. එක් එක් ටැගය සඳහා වෙනම සැරසිලි කරුවන් භාවිතා කිරීමෙන්.

මේ සඳහා සැරසිලි කරුවා තුළම වැඩි කේතයක් අවශ්‍ය වේ, නමුත් මෙය ක්‍රියාත්මක වන්නේ එය ක්‍රියාකාරී අර්ථ දැක්වීම් සඳහා යොදන විට පමණි, පසුව ඒවා හැඳින්වූ විට නොවේ. lambdaකලින් නිදර්ශනය කර ඇති පරිදි කාර්යයන් භාවිතා කරමින් වඩාත් කියවිය හැකි නම් නිර්මාණය කිරීමේදී ද මෙය අදාළ වේ . නියැදිය:

def multi_html_deco(*tags):
    start_tags, end_tags = [], []
    for tag in tags:
        start_tags.append('<%s>' % tag)
        end_tags.append('</%s>' % tag)
    start_tags = ''.join(start_tags)
    end_tags = ''.join(reversed(end_tags))

    def decorator(fn):
        @wraps(fn)
        def wrapped(*args, **kwargs):
            return start_tags + fn(*args, **kwargs) + end_tags
        return wrapped
    return decorator

makebolditalic = multi_html_deco('b', 'i')

@makebolditalic
def greet(whom=''):
    return 'Hello' + (' ' + whom) if whom else ''

print(greet('world'))  # -> <b><i>Hello world</i></b>

2
DRY වෙත යොමු කිරීම සඳහා upvote :-)
nitin3685

"@ රැප්ස් (විනෝද)" පැහැදිලි කිරීම සඳහා ස්තූතියි :)
ඇවිදීමේ සටහන්

20

එකම දේ කිරීමේ තවත් ක්‍රමයක්:

class bol(object):
  def __init__(self, f):
    self.f = f
  def __call__(self):
    return "<b>{}</b>".format(self.f())

class ita(object):
  def __init__(self, f):
    self.f = f
  def __call__(self):
    return "<i>{}</i>".format(self.f())

@bol
@ita
def sayhi():
  return 'hi'

නැතහොත්, වඩාත් නම්‍යශීලීව:

class sty(object):
  def __init__(self, tag):
    self.tag = tag
  def __call__(self, f):
    def newf():
      return "<{tag}>{res}</{tag}>".format(res=f(), tag=self.tag)
    return newf

@sty('b')
@sty('i')
def sayhi():
  return 'hi'

functools.update_wrapperතබා ගැනීම සඳහා අවශ්‍යයිsayhi.__name__ == "sayhi"
එරික්

19

පයිතන් හි සැරසිලි කරුවන් දෙදෙනෙකු සාදා ගන්නේ කෙසේද?

කැඳවූ විට ඔබට පහත ශ්‍රිතය අවශ්‍ය වේ:

@makebold
@makeitalic
def say():
    return "Hello"

ආපසු යාමට:

<b><i>Hello</i></b>

සරල විසඳුමක්

වඩාත් සරළව මෙය සිදු කිරීම සඳහා, ශ්‍රිතය (වසා දැමීම්) වසා දැමූ ලැම්බඩාස් (නිර්නාමික කාර්යයන්) ආපසු ලබා දෙන සැරසිලි කරුවන් අමතන්න:

def makeitalic(fn):
    return lambda: '<i>' + fn() + '</i>'

def makebold(fn):
    return lambda: '<b>' + fn() + '</b>'

දැන් ඒවා අවශ්‍ය පරිදි භාවිතා කරන්න:

@makebold
@makeitalic
def say():
    return 'Hello'

සහ දැන්:

>>> say()
'<b><i>Hello</i></b>'

සරල විසඳුම සමඟ ගැටළු

නමුත් අපට මුල් ශ්‍රිතය නැති වී ඇති බව පෙනේ.

>>> say
<function <lambda> at 0x4ACFA070>

එය සොයා ගැනීම සඳහා, එක් එක් ලැම්බඩා වසා දැමීම පිළිබඳව අප හාරා බැලිය යුතුය, ඉන් එකක් වළලනු ලැබේ:

>>> say.__closure__[0].cell_contents
<function <lambda> at 0x4ACFA030>
>>> say.__closure__[0].cell_contents.__closure__[0].cell_contents
<function say at 0x4ACFA730>

එබැවින් අපි මෙම ශ්‍රිතය පිළිබඳ ලියකියවිලි තැබුවහොත් හෝ තර්ක එකකට වඩා වැඩි ප්‍රමාණයක් අලංකාර කිරීමට අවශ්‍ය නම්, හෝ නිදොස් කිරීමේ සැසියකදී අප බලා සිටියේ කුමන ශ්‍රිතයක් දැයි දැන ගැනීමට අපට අවශ්‍ය නම්, අප සමඟ තව ටිකක් කළ යුතුය වැස්ම.

සම්පුර්ණ විශේෂාංග විසඳුම - මෙම ගැටළු බොහොමයක් ජය ගැනීම

අපි decorator ඇති wrapsවෙතින් functoolsසම්මත පුස්තකාලයේ මොඩියුලය!

from functools import wraps

def makeitalic(fn):
    # must assign/update attributes from wrapped function to wrapper
    # __module__, __name__, __doc__, and __dict__ by default
    @wraps(fn) # explicitly give function whose attributes it is applying
    def wrapped(*args, **kwargs):
        return '<i>' + fn(*args, **kwargs) + '</i>'
    return wrapped

def makebold(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return '<b>' + fn(*args, **kwargs) + '</b>'
    return wrapped

තවමත් බොයිලේරු කිහිපයක් තිබීම අවාසනාවකි, නමුත් මෙය අපට සෑදිය හැකි තරම් සරල ය.

Python 3, ඔබ ලබා ගන්න __qualname__සහ __annotations__පෙරනිමි මගින් පවරා ඇති.

ඉතින් දැන්:

@makebold
@makeitalic
def say():
    """This function returns a bolded, italicized 'hello'"""
    return 'Hello'

සහ දැන්:

>>> say
<function say at 0x14BB8F70>
>>> help(say)
Help on function say in module __main__:

say(*args, **kwargs)
    This function returns a bolded, italicized 'hello'

නිගමනය

ඉතින් අපි ඒක දකිනවා wraps , ශ්‍රිතය තර්ක ලෙස ගත යුතු දේ හරියටම අපට පැවසීම හැර, එතීමේ කාර්යය සෑම දෙයක්ම පාහේ සිදු කරයි.

ගැටළුව විසඳීමට උත්සාහ කළ හැකි වෙනත් මොඩියුලයන් ඇත, නමුත් විසඳුම තවමත් සම්මත පුස්තකාලයේ නොමැත.


14

සැරසිලි කරුවා සරල ආකාරයකින් පැහැදිලි කිරීම සඳහා:

සමඟ:

@decor1
@decor2
def func(*args, **kwargs):
    pass

කළ යුත්තේ කවදාද:

func(*args, **kwargs)

ඔබ ඇත්තටම කරන්නේ:

decor1(decor2(func))(*args, **kwargs)

13

සැරසිලි කරුවෙකු ශ්‍රිත අර්ථ දැක්වීම ගෙන නව ශ්‍රිතයක් නිර්මාණය කර මෙම ශ්‍රිතය ක්‍රියාත්මක කර ප්‍රති .ලය පරිවර්තනය කරයි.

@deco
def do():
    ...

සමාන වේ:

do = deco(do)

උදාහරණයක්:

def deco(func):
    def inner(letter):
        return func(letter).upper()  #upper
    return inner

මෙය

@deco
def do(number):
    return chr(number)  # number to letter

මෙයට සමාන වේ

def do2(number):
    return chr(number)

do2 = deco(do2)

65 <=> 'අ'

print(do(65))
print(do2(65))
>>> B
>>> B

සැරසිලි කරුවා තේරුම් ගැනීම සඳහා, සැරසිලි කරුවා විසින් නව ශ්‍රිතයක් නිර්මාණය කර ඇති අතර එය අභ්‍යන්තරය වන අතර එය ක්‍රියාකාරීත්වය ක්‍රියාත්මක කරන අතර ප්‍රති .ලය පරිවර්තනය කරයි.


ප්රතිදානය නොකළ යුතුය print(do(65))හා print(do2(65))විය Aහා A?
ට්‍රීෆිෂ් ෂැං

8
#decorator.py
def makeHtmlTag(tag, *args, **kwds):
    def real_decorator(fn):
        css_class = " class='{0}'".format(kwds["css_class"]) \
                                 if "css_class" in kwds else ""
        def wrapped(*args, **kwds):
            return "<"+tag+css_class+">" + fn(*args, **kwds) + "</"+tag+">"
        return wrapped
    # return decorator dont call it
    return real_decorator

@makeHtmlTag(tag="b", css_class="bold_css")
@makeHtmlTag(tag="i", css_class="italic_css")
def hello():
    return "hello world"

print hello()

ඔබට පන්තියේ සැරසිලි කරන්නෙකු ලිවිය හැකිය

#class.py
class makeHtmlTagClass(object):
    def __init__(self, tag, css_class=""):
        self._tag = tag
        self._css_class = " class='{0}'".format(css_class) \
                                       if css_class != "" else ""

    def __call__(self, fn):
        def wrapped(*args, **kwargs):
            return "<" + self._tag + self._css_class+">"  \
                       + fn(*args, **kwargs) + "</" + self._tag + ">"
        return wrapped

@makeHtmlTagClass(tag="b", css_class="bold_css")
@makeHtmlTagClass(tag="i", css_class="italic_css")
def hello(name):
    return "Hello, {}".format(name)

print hello("Your name")

1
මෙහි පන්තියකට කැමති වීමට හේතුව පැහැදිලිව ආශ්‍රිත හැසිරීම් ඇති අතර අවස්ථා දෙකක් ඇත. පරාමිතීන් නැවත නැවත සැකසීමට වඩා, ඔබට අවශ්‍ය නම් වලට ඉදිකරන ලද පන්ති පැවරීමෙන් ඔබට සැබවින්ම ඔබේ සැරසිලි කරුවන් දෙදෙනා ලබා ගත හැකිය. මෙය ශ්‍රිතයක් සමඟ කිරීමට අපහසුය. එය නිදසුනකට එකතු කිරීමෙන් මෙය අතිරික්ත නොවන්නේ මන්දැයි පෙන්වා දෙනු ඇත.
ජෝන් ජේ ඔබර්මාර්ක්

8

මෙම පිළිතුරට බොහෝ කලකට පිළිතුරු ලැබී ඇත, නමුත් නව සැරසිලි කරුවන් ලිවීම පහසු සහ සංයුක්ත කරන මගේ සැරසිලි පන්තිය බෙදා ගැනීමට මම සිතුවෙමි.

from abc import ABCMeta, abstractclassmethod

class Decorator(metaclass=ABCMeta):
    """ Acts as a base class for all decorators """

    def __init__(self):
        self.method = None

    def __call__(self, method):
        self.method = method
        return self.call

    @abstractclassmethod
    def call(self, *args, **kwargs):
        return self.method(*args, **kwargs)

කෙනෙකුට මම සිතන්නේ මෙය සැරසිලි කරුවන්ගේ හැසිරීම ඉතා පැහැදිලිව පෙනෙන නමුත් නව සැරසිලි කරුවන් ඉතා සංක්ෂිප්තව අර්ථ දැක්වීම පහසු කරයි. ඉහත ලැයිස්තුගත කර ඇති උදාහරණය සඳහා, ඔබට එය මෙසේ විසඳිය හැකිය:

class MakeBold(Decorator):
    def call():
        return "<b>" + self.method() + "</b>"

class MakeItalic(Decorator):
    def call():
        return "<i>" + self.method() + "</i>"

@MakeBold()
@MakeItalic()
def say():
   return "Hello"

වඩාත් සංකීර්ණ කාර්යයන් සඳහා ඔබට එය භාවිතා කළ හැකිය, නිදසුනක් ලෙස සැරසිලි කරුවෙකු ස්වයංක්‍රීයව ශ්‍රිතය ස්වයංක්‍රීයව පුනරාවර්තව අනුකාරකයේ ඇති සියලුම තර්ක වලට අදාළ කරවයි:

class ApplyRecursive(Decorator):
    def __init__(self, *types):
        super().__init__()
        if not len(types):
            types = (dict, list, tuple, set)
        self._types = types

    def call(self, arg):
        if dict in self._types and isinstance(arg, dict):
            return {key: self.call(value) for key, value in arg.items()}

        if set in self._types and isinstance(arg, set):
            return set(self.call(value) for value in arg)

        if tuple in self._types and isinstance(arg, tuple):
            return tuple(self.call(value) for value in arg)

        if list in self._types and isinstance(arg, list):
            return list(self.call(value) for value in arg)

        return self.method(arg)


@ApplyRecursive(tuple, set, dict)
def double(arg):
    return 2*arg

print(double(1))
print(double({'a': 1, 'b': 2}))
print(double({1, 2, 3}))
print(double((1, 2, 3, 4)))
print(double([1, 2, 3, 4, 5]))

කුමන මුද්‍රණ:

2
{'a': 2, 'b': 4}
{2, 4, 6}
(2, 4, 6, 8)
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

මෙම උදාහරණයේ listසැරසිලි කරුවාගේ ක්ෂණික වර්ගය ඇතුළත් නොවන බව සලකන්න , එබැවින් අවසාන මුද්‍රණ ප්‍රකාශයේ දී ලැයිස්තුවට අදාළ වන්නේ ලැයිස්තුවේ මූලද්‍රව්‍ය නොව ලැයිස්තුවට ය.


7

දම්වැල් සැරසිලි කරුවන් සඳහා සරල උදාහරණයක් මෙන්න. අන්තිම පේළිය සටහන් කරන්න - එය ආවරණ යටතේ සිදුවන්නේ කුමක්ද යන්න පෙන්වයි.

############################################################
#
#    decorators
#
############################################################

def bold(fn):
    def decorate():
        # surround with bold tags before calling original function
        return "<b>" + fn() + "</b>"
    return decorate


def uk(fn):
    def decorate():
        # swap month and day
        fields = fn().split('/')
        date = fields[1] + "/" + fields[0] + "/" + fields[2]
        return date
    return decorate

import datetime
def getDate():
    now = datetime.datetime.now()
    return "%d/%d/%d" % (now.day, now.month, now.year)

@bold
def getBoldDate(): 
    return getDate()

@uk
def getUkDate():
    return getDate()

@bold
@uk
def getBoldUkDate():
    return getDate()


print getDate()
print getBoldDate()
print getUkDate()
print getBoldUkDate()
# what is happening under the covers
print bold(uk(getDate))()

ප්‍රතිදානය පෙනේ:

17/6/2013
<b>17/6/2013</b>
6/17/2013
<b>6/17/2013</b>
<b>6/17/2013</b>

6

කවුන්ටරයේ උදාහරණය ගැන කථා කිරීම - ඉහත දක්වා ඇති පරිදි, සැරසිලි කරුවා භාවිතා කරන සියලුම කාර්යයන් අතර කවුන්ටරය බෙදා ගනු ඇත:

def counter(func):
    def wrapped(*args, **kws):
        print 'Called #%i' % wrapped.count
        wrapped.count += 1
        return func(*args, **kws)
    wrapped.count = 0
    return wrapped

ඒ ආකාරයෙන්, ඔබේ සැරසිලි කරුවා විවිධ කාර්යයන් සඳහා නැවත භාවිතා කළ හැකිය (හෝ එකම ශ්‍රිතය කිහිප වතාවක් අලංකාර කිරීම සඳහා භාවිතා කරයි :) func_counter1 = counter(func); func_counter2 = counter(func), සහ කවුන්ටරයේ විචල්‍යය එක් එක් පුද්ගලයාට පුද්ගලිකව පවතිනු ඇත.


6

විවිධ තර්ක ගණනකින් කාර්යයන් අලංකාර කරන්න:

def frame_tests(fn):
    def wrapper(*args):
        print "\nStart: %s" %(fn.__name__)
        fn(*args)
        print "End: %s\n" %(fn.__name__)
    return wrapper

@frame_tests
def test_fn1():
    print "This is only a test!"

@frame_tests
def test_fn2(s1):
    print "This is only a test! %s" %(s1)

@frame_tests
def test_fn3(s1, s2):
    print "This is only a test! %s %s" %(s1, s2)

if __name__ == "__main__":
    test_fn1()
    test_fn2('OK!')
    test_fn3('OK!', 'Just a test!')

ප්‍රති ult ලය:

Start: test_fn1  
This is only a test!  
End: test_fn1  


Start: test_fn2  
This is only a test! OK!  
End: test_fn2  


Start: test_fn3  
This is only a test! OK! Just a test!  
End: test_fn3  

1
def wrapper(*args, **kwargs):සහ හරහා ප්‍රධාන වචන තර්ක සඳහා සහය ලබා දීමෙන් මෙය පහසුවෙන් වඩාත් විවිධාකාර කළ හැකිය fn(*args, **kwargs).
මාර්ටිනෝ

5

පාඔලෝ Bergantino පිළිතුර එම stdlib භාවිතා කරන එකම මහා වාසිය, සහ නැත කොහෙද මේ සරල උදාහරණයක් සඳහා ක්රියා decorator තර්ක හෝ සරසා උත්සවය තර්ක.

කෙසේ වෙතත් ඔබට වඩාත් පොදු අවස්ථා විසඳීමට අවශ්‍ය නම් එයට ප්‍රධාන සීමාවන් 3 ක් ඇත:

  • පිළිතුරු කිහිපයක දැනටමත් සඳහන් කර ඇති පරිදි, විකල්ප සැරසිලි තර්ක එකතු කිරීම සඳහා ඔබට කේතය පහසුවෙන් වෙනස් කළ නොහැක . උදාහරණයක් ලෙස amakestyle(style='bold') සැරසිලි කරුවෙකු සුළුපටු නොවේ.
  • ඊට අමතරව, සාදන ලද එතීමෙන් @functools.wraps අත්සන ආරක්ෂා නොවේ , එබැවින් නරක තර්ක සපයන්නේ නම් ඒවා ක්‍රියාත්මක කිරීමට පටන් ගන්නා අතර වෙනදාට වඩා වෙනස් ආකාරයේ දෝෂයක් මතු විය හැකිය TypeError.
  • අවසාන වශයෙන්, එහි නම මත පදනම්ව තර්කයක්@functools.wraps වෙත ප්‍රවේශ වීම සඳහා නිර්මාණය කරන ලද එතුමෙහි තරමක් දුෂ්කර ය . ඇත්ත වශයෙන්ම තර්කය කිසිසේත්ම දර්ශනය විය හැකිය *args, ඇතුළත **kwargsහෝ නොපෙන්වයි (එය විකල්ප නම්).

මම decopatchපළමු ප්‍රශ්නය makefun.wrapsවිසඳීමට ලිවූ අතර අනෙක් කරුණු දෙක විසඳීමට ලිව්වෙමි. makefunසුප්‍රසිද්ධ decoratorලිබ් වලට වඩා එකම උපක්‍රමය භාවිතා කරන බව සලකන්න .

මෙය ඔබ තර්ක සමඟ සැරසිලි කරුවෙකු නිර්මාණය කරන්නේ කෙසේද, සැබවින්ම අත්සන ආරක්ෂා කරන එතුම නැවත ලබා දෙයි:

from decopatch import function_decorator, DECORATED
from makefun import wraps

@function_decorator
def makestyle(st='b', fn=DECORATED):
    open_tag = "<%s>" % st
    close_tag = "</%s>" % st

    @wraps(fn)
    def wrapped(*args, **kwargs):
        return open_tag + fn(*args, **kwargs) + close_tag

    return wrapped

decopatchඔබේ මනාපයන් මත පදනම්ව විවිධ පයිතන් සංකල්ප සැඟවීමට හෝ පෙන්වීමට තවත් සංවර්ධන ශෛලීන් දෙකක් ඔබට සපයයි. වඩාත්ම සංයුක්ත විලාසය පහත දැක්වේ:

from decopatch import function_decorator, WRAPPED, F_ARGS, F_KWARGS

@function_decorator
def makestyle(st='b', fn=WRAPPED, f_args=F_ARGS, f_kwargs=F_KWARGS):
    open_tag = "<%s>" % st
    close_tag = "</%s>" % st
    return open_tag + fn(*f_args, **f_kwargs) + close_tag

මෙම අවස්ථා දෙකෙහිම සැරසිලි කරුවා අපේක්ෂිත පරිදි ක්‍රියා කරන බව ඔබට පරීක්ෂා කළ හැකිය:

@makestyle
@makestyle('i')
def hello(who):
    return "hello %s" % who

assert hello('world') == '<b><i>hello world</i></b>'    

වැඩි විස්තර සඳහා කරුණාකර ප්‍රලේඛනය බලන්න.

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.