Global () Returns the property dictionary for the global scope, locals () returns the property dictionary for the local scope. The value returned when locals () is positioned at the top level of the module is the same as global ().
Instance
#!/usr/bin/python#coding =utf-8 class Dog(object):x = Oney = A def __init__(self):m = -n = - def eat(self):K = Oneh = A ' print {' H ': ' K ': One, ' self ': <__main__. Dog object at 0x7fc2985b8e10>} " PrintLocals () def func():x =1y =2 def wrap(): Pass "Print Func Local is: {' wrap ': <function wrap at 0x7fc2985be938>, ' Y ': 2, ' X ': 1} " Print ' Func Local is:%s '% locals () x =1y =2Func ()' Both print {' __builtins__ ': <module ' __builtin__ ' (built-in), ' __file__ ': ' t.py ', ' Dog ': <class ' __main__. Dog ', ' __package__ ': None, ' func ': <function func at 0x7fc2985be7d0>, ' x ': 1, ' Y ': 2, ' __name__ ': ' __main__ ', ' _ _doc__ ': None} 'Print ' Local is:%s '% locals ()Print ' Globals is:%s '%globals () dog = Dog () dog.eat ()
Output
FuncLocalis: {' Wrap ': < function wrap at 0x7febea277938, ' y ': 2, ' x ' : 1}Localis: {' __builtins__ ': <module' __builtin__ '(built-inch);' __file__ ':' t.py ',' Dog ': <class' __main__. Dog ',' __package__ ': None,' func ': < function func at 0x7febea2777d0, ' x ': 1, ' Y ': 2, ' __name__ ': ' __main__ ', ' __doc__ ': None}Globalsis: {' __builtins__ ': <module' __builtin__ '(built-inch);' __file__ ':' t.py ',' Dog ': <class' __main__. Dog ',' __package__ ': None,' func ': < function func at 0x7febea2777d0, ' x ': 1, ' y ': 2, ' __name__ ': ' __main__ ', ' __doc__ ': None}{' h ': A,' K ': One,' self ': <__main__. Dog Object at 0x7febea271e10}
Python's Globals () and locals ()