Python video tutorialExplaining decorators
Decorator concept
Decorator, to put it bluntly, is afunction## 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.
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()
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
@wrapperQuickly 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(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>
##It can be seen from this
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!

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

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

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

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

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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 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
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
