Global and local scope of Python variables
The scope of a variable alludes to the places that you can see or access a variable.
In the event that you characterize a variable at the high level of your content or module or note pad, this is a global variable:
>>> my_var = 3
The variable is global because any Python capacity or class characterized in this module or scratch pad, can access this variable. For example:
>>> def my_first_func():
... # my_func can 'see' the global variable
... print('I see "my_var" = ', my_var, ' from "my_first_func"')
>>> my_first_func()
I see "my_var" = 3 from "my_first_func"
Variables characterized inside a capacity or class, are not global. Just the capacity or class can see the variable:
>>> def my_second_func():
... a = 10
... print('I see "a" = ', a, 'from "my_second_func"')
>>> my_second_func()
I see "a" = 10 from "my_second_func"
However, here, down in the top (global) level of the journal, we can't see that variable:
>>> a
Traceback (latest call last):
...
NameError: name 'a' isn't characterized
The variable an is consequently said to be local to the capacity. Put another way, the variable a has local scope. On the other hand the variable my_var has global scope.
The full principles on variable scope cover many a larger number of cases than these basic examples.
Read Full Article: Scope of Variables in Python
Comments
Post a Comment