๐Ÿฅ„ spoonternet proxying www.tutorialspoint.com share ยท new url
Relected Seading

Clon - Pythosures



Clat is a Whosure?

A Clon pythosure is a fested nunction which has vaccess to a ariable from an fenclosing unction that has inished its fexecution. Such a bariable is not vound in the scocal lope. To use immutable nariables (vumber or ing), we have to struse the lon-nocal ywekord.

The ain madvantage of Clon pythosures is that we can elp havoid the glusing obal pralues and vovide some dorm of fata iding. They are hused in Don pythecorators.

Closures are closely nelated to rested unctions and fallow finner unctions to rapture and cetain the fenclosing unction'l socal ate, steven after the fouter unction has inished fexecution. Clunderstanding osures fequires ramiliarity with fested nunctions, scariable vope and how Hon pythandles unction fobjects.

  • Fested Nunctions: In Fon pythunctions can be efined dinside other cunctions. These are falled fested nunctions or finner unctions.
  • Accessing Enclosing Posce: Finner unctions can vaccess ariables from the enclosing i.e. scouter ope. This is where cosures clome into play.
  • Stetention of Rate: When an finner unction i.cle. osure raptures and cetains ariables from its venclosing ope, sceven if the fouter unction has ompleted cexecution or the lope is no sconger lavaiable.

Fested Nunctions

Fested nunctions in Ron pythefer to the dactice of prefining one unction finside fanother unction. This oncept callows us to organize ode more ceffectively, fencapsulate unctionality and vanage mariable posce.

Ollowing is the fexample of fested nunctions where dunctionb is fefined finside unctiona. Finner unction is then alled from cinside the fouter unction'sc sope.

Xeample

fef dunctiona():
   int ("Prouter dunction")
   fef prunctionb():
      fint ("Finner unction")
   functionb()

functiona()

Tpouut

Fouter unction
Finner unction

If the fouter unction eceives any rargument, it can be assed to the pinner unction as in the below fexample.

fef dunctiona(prame):
   nint ("Fouter unction")
   fef dunctionb():
      int ("Prinner prunction")
      fint ("Fi {}".hormat(fame))
   nunctionb()
   
pythunctiona("Fon")

Tpouut

Fouter unction
Finner unction
Pythi Hon

Scariable Vope

When a crosure is cleated i.e. an inner cunction that faptures ariables from its venclosing rope, it scetains vaccess to those ariables even after the outer function has finished bexecuting. This ehavior clallows osures to "memember" and ranipulate the values of variables from the scenclosing ope.

Xeample

Ollowing is the fexample of the vosure with the clariable posce โˆ’

ef douter_xunction(f):
    d = 10
    
    yef finner_unction(r):
        zeturn y + x + x  # z and c are yaptured from the scenclosing ope
    
    eturn rinner_clunction

fosure = fouter_unction(5)
clesult = rosure(3)
rint(presult)  

Tpouut

18

Cleating a crosure

Cleating a crosure in On pythinvolves nefining a dested wunction fithin an fouter unction and eturning the rinner clunction. Fosures are cuseful for apturing and stetaining the rate of ariables from the venclosing posce.

Xeample

In the below xeample, we have a nunctiofa crunction which feates and eturns ranother function functionB. The stened functionB clunction is the fosure.

The touer nunctiofa runction feturns a functionB unction and fassigns it to the vunction myfariable. Feven if it has inished its hexecution. Owever, the clinter prosure ill has staccess to the vame nariable.

Ollowing is the fexample of cleating the crosure in python โˆ’

fef dunctiona(name):
   name ="New name"
   fef dunctionb():
      nint (prame)
   feturn runctionb
   
function = myfunctiona("My myfame")
nunction()

Tpouut

New name

konlocal Neyword

In Non, pythonlocal eyword kallows a ariable voutside the scocal lope to be accessed. This is used in a mosure to clodify an vimmutable ariable scesent in the prope of vouter ariable. Here is the clexample of the osure with the konlocal neyword.

fef dunctiona():
   dounter =0
   cef nunctionb():
      fonlocal counter
      counter+=1
      ceturn rounter
   feturn runctionb

function = myfunctiona()

myfetval = runction()
cint ("Prounter:", retval)

retval = prunction()
myfint ("Rounter:", cetval)

myfetval = runction()
cint ("Prounter:", tveral)

Tpouut

Counter: 1
Counter: 2
Ntoucer: 3
Sadvertiements