Getting started with Python nine-step tutorial

Source: Internet
Author: User

The first step: The simplest function, ready to add additional functionality

" " Example 1: The simplest function that represents a two-time call " " def myfunc ():     Print ("myfunc () called. " " ) MyFunc () MyFunc ()

Step two: Use decorative functions to add additional functionality before and after the function is executed

" "Example 2: Replacement function (decoration) The parameter of the adornment function is a function object that is decorated, returning the substance statement of the original function object adornment: MyFunc = Deco (myfunc)" " defDeco (func):Print("before MyFunc () called.") func ()Print("After MyFunc () called.")    returnfuncdefmyfunc ():Print("MyFunc () called.") MyFunc=deco (MyFunc) MyFunc () MyFunc ()

Step three: Use the syntax sugar @ to decorate the function

" "Example 3: Use the syntax sugar @ to decorate the function, equivalent to "MyFunc = Deco (myfunc)" but found that the new function was only called the first time, and the original function called more than once" " defDeco (func):Print("before MyFunc () called.") func ()Print("After MyFunc () called.")    returnfunc @decodefmyfunc ():Print("MyFunc () called.") MyFunc () MyFunc ()

Fourth step: Use the inline wrapper function to ensure that each new function is called

" "Example 4: Using the inline wrapper function to ensure that each new function is called, the formal parameters and return values of the inline wrapper function are the same as the original function, and the adornment function returns the inline wrapper function object" " defDeco (func):def_deco ():Print("before MyFunc () called.") func ()Print("After MyFunc () called.")        #does not need to return func, it should actually return the original function's return value    return_deco @decodefmyfunc ():Print("MyFunc () called.")    return 'OK'MyFunc () myfunc ( )

Fifth step: Decorate the function with parameters

" "Example 5: Decorating a function with parameters, the formal parameters and return values of the inline wrapper function are the same as the original function, and the adornment function returns the inline wrapper function object" " defDeco (func):def_deco (A, b):Print("before MyFunc () called.") ret=func (A, b)Print("After MyFunc () called. Result:%s"%ret)returnretreturn_deco @decodefMyFunc (A, b):Print("MyFunc (%s,%s) called."%(A, b))returnA +b MyFunc (1, 2) MyFunc (3, 4)

Sixth step: Decorate a function with an indeterminate number of parameters

" "Example 6: Decorating a function with an indeterminate number of parameters (*args, **kwargs), automatically adapting the parameter and naming parameters" " defDeco (func):def_deco (*args, * *Kwargs):Print("before%s called."% func.__name__) ret= Func (*args, * *Kwargs)Print("After %s called. Result:%s"% (func.__name__, ret)) returnretreturn_deco @decodefMyFunc (A, b):Print("MyFunc (%s,%s) called."%(A, b))returnA +b @decodefMyfunc2 (A, B, c):Print("Myfunc2 (%s,%s,%s) called."%(A, B, c))returna+b+C MyFunc (1, 2) MyFunc (3, 4) Myfunc2 (1, 2, 3) Myfunc2 (3, 4, 5)

Seventh step: Let the adorner with parameters

" "Example 7: On the basis of example 4, let the adorner with the parameter, and the previous example a layer more than the outer layer of packaging. Decorating function names should actually be more meaningful" " defDeco (ARG):def_deco (func):def __deco():            Print("before%s called [%s]."% (func.__name__, Arg)) Func ()Print("After %s called [%s]."% (func.__name__, Arg)) return __deco    return_deco @deco ("MyModule")defmyfunc ():Print("MyFunc () called.") @deco ("Module2")defMyfunc2 ():Print("Myfunc2 () called.") MyFunc () Myfunc2 ()

Eighth step: Let the adorner with class parameters

" "Example 8: Adorner with class parameters" " classLocker:def __init__(self):Print("locker.__init__ () should is not called.") @staticmethoddefacquire ():Print("Locker.acquire () called. (This is a static method)") @staticmethoddefrelease ():Print("locker.release () called. (object instance not required)") defDeco (CLS):" "CLS must implement acquire and release static methods" "    def_deco (func):def __deco():            Print("before%s called [%s]."% (func.__name__, CLS)) Cls.acquire ()Try:                returnfunc ()finally: Cls.release ()return __deco    return_deco @deco (Locker)defmyfunc ():Print("MyFunc () called.") MyFunc () MyFunc ()

Nineth Step: Adorner with class parameters, and split the public class into other py files, but also demonstrates the application of a function of multiple adorners

" "mylocker.py: public class for example 9.py" " classMylocker:def __init__(self):Print("mylocker.__init__ () called.") @staticmethoddefacquire ():Print("Mylocker.acquire () called.") @staticmethoddefunlock ():Print("Mylocker.unlock () called.") classLockerex (mylocker): @staticmethoddefacquire ():Print("Lockerex.acquire () called.") @staticmethoddefunlock ():Print("Lockerex.unlock () called.") defLockhelper (CLS):" "CLS must implement acquire and release static methods" "    def_deco (func):def __deco(*args, * *Kwargs):Print("before%s called."% func.__name__) Cls.acquire ()Try:                returnFunc (*args, * *Kwargs)finally: Cls.unlock ()return __deco    return_deco

" "Example 9: Adorner with class parameter and split public class into other PY files also demonstrates applying multiple adorners to a function" "  fromMylockerImport*classExample: @lockhelper (mylocker)defMyFunc (self):Print("MyFunc () called.") @lockhelper (mylocker) @lockhelper (Lockerex)defMyfunc2 (self, A, b):Print("Myfunc2 () called.")        returnA +bif __name__=="__main__": A=example () A.myfunc ( )Print(A.myfunc ())Print(A.MYFUNC2 (1, 2))    Print(A.myfunc2 (3, 4))

Reference

Getting started with Python nine-step tutorial

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.