search
HomeBackend DevelopmentPython TutorialPython basics decorators and exercises

Python basics decorators and exercises

Dec 22, 2020 pm 05:45 PM
pythonDecorator

Python video tutorialExplaining decorators

Python basics decorators and exercises

##Recommended free:

Python video tutorial

Decorator concept

Decorator, to put it bluntly, is a

function## used to decorate functions. #. The decorator follows the open-closed principle
and dependency inversion principle. These two principles and concepts can be found on Baidu.

What does the decorator look like?

def wrapper(f): 
    def inner(*args,**kwargs):  
        ret = f(*args,**kwargs)
        return ret
    return inner
The above code is the fixed format of the decorator

Calling the decorator

@wrapper  # 简称语法糖
def test():
    print(1)
test()

@wrapper

is calling the decorator, Compared with wrapper(test()), it saves code and is more beautiful. Maybe you don’t understand when you see this, why do you need @wrapper? The calling function is not wrapper()? Actually, if you ask me to tell you, I don’t know. I just know that it is easier to write this way. Directly in front of the function to be decorated@wrapper
Quickly understand the decorator with a small example

def wrapper(f):
    print(2)
    def inner(*args,**kwargs):
        print(3)
        ret = f(*args,**kwargs)
        print(4)
        return ret
    return inner


@wrapper
def test():
    print(1)
test()

@wrapper

== wrapper(test()) It is equivalent to calling the decorator function. It will be easier to directly use the syntax sugar @wrapper*args
is the matching For positional parameters, **kwargs matches parameters passed by keyword, so that all parameters can be received. wrapper(test)
Receives the value and passes it to f. In the inner circle function, ret = f(*args,**kwargs)This function is Code that executes the decorated function. Then return the executed value, and finally return this function. The execution result of this code is: <pre class="brush:php;toolbar:false">2 3 1 4</pre>

As shown in the figure below

Python basics decorators and exercises##It can be seen from this

## In #function

inner, print(3)
is the operation before executing the decoration function, and print(4) is the operation after executing the decoration function. It may be difficult to understand. So it’s best to give it a try. Basic exercises

'''1. 默写装饰器固定格式
  2. 写一个加减功能的装饰器
'''

The above is the detailed content of Python basics decorators and exercises. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:简书. If there is any infringement, please contact admin@php.cn delete
How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

How does the memory footprint of a list compare to the memory footprint of an array in Python?How does the memory footprint of a list compare to the memory footprint of an array in Python?May 02, 2025 am 12:08 AM

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

How do you handle environment-specific configurations when deploying executable Python scripts?How do you handle environment-specific configurations when deploying executable Python scripts?May 02, 2025 am 12:07 AM

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment