PYTHON NAMESPACE AND
SCOPE
Namespaces
a=2
b=2
print("a=",id(a))
print("b=",id(b))
#The
above print statement print both id is same
#Even
you try to print
print(id(2)) #it
is also the same id of a & b
#python
interpreter dynamically map the name space
c="hai"
d="xyz"
e="hai"
#the
above assignment c and e refer the same name space but d is
different
print("id(c)=",id(c))
print("id(e)=",id(e))
print("id(d)=",id(d))
output:
a=505910976
b=505910976
505910976
id(c)=36027328
id(e)=36027328
id(d)=36012960
#Note :you may get different value of id
a=2
print('id(2)=',id(2))
#output:
id(2)=10919424
print('id(a)=',id(a))
#output:
id(a)=10919424
#Here ,both refer to the same object.
Let's make things #a little more interesting.
#Note :you may get different
value of id
a=2
print('id(a)=',id(a))
#output:
id(a)=10919424
a=a+1
print ('id(a)=',id(a))
#output:
id(a=10919456)
print('id(3)=',id(3))
#output:
id(3)=10919456
b=2
print('id(2)=',id(2))
#output:
id(2)=10919424
Python Namespace
Namespace is a
Collection of names.
python variable scope
Program1
def
outer_function():
b=20
def
inner_func():
c=30
a=10
Program2
def
outer_function():
a=20
def
inner_function():
a=30
print('a=',a)
inner_function()
print('a=',a)
a=10
outer_function()
print('a=',a)
output:
a=30
a=20
a=10
Program 3
we declare a as
global the variable will be set in globally and prints all function in that
global variable 30
def
outer_function():
global
a
a=20
def
inner_function():
global
a
a=30
print('a=',a)
inner_function()
print('a=',a)
a=10
outer_function()
print('a=',a)
output:
a=30
a=30
a=30
0 comments:
Post a Comment