LEGB rule
Scope also defines the order in which variables
have to be mapped to the object in order to obtain the value. Let us take a
simple example as shown below:
x:= 'outer x variable'
display():
x:= 'inner x variable'
print x
display()
When the above statements are executed the
statement (4) and (5) display the result as
Output
outer x variable
inner x variable
Above statements give different outputs because
the same variable name x resides in different scopes, one
inside the function display() and the other in the upper level. The value ‘outer
xvariable’ is printed when x is referenced outside the function
definition. Whereas when display() gets executed, ‘inner x variable’ is
printed which is the x value inside the function
definition. From the above example, we can guess that there is a rule followed,
in order to decide from which scope a variable has to be picked.
The LEGB rule is used to decide the
order in which the scopes are to be searched for scope resolution. The scopes
are listed below in terms of hierarchy (highest to lowest).
Local(L) : Defined inside function/class
Enclosed(E) : Defined inside enclosing
functions (Nested function concept)
Global(G) : Defined at the uppermost level
Built-in (B) : Reserved names in built-in
functions (modules)
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.