Posted By

magicrebirth on 12/22/09


Tagged

class python module namespace


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

gartenstuhl


Python: module and class namespaces


 / Published in: Python
 

  1. ## The module namespace is created when a module is imported and the objects within the module are read. The module namespace can be accessed using the .__dict__ attribute of the module object. Objects in the module namespace can be accessed directly using the module name and dot "." syntax. The example shows this by calling the localtime() function of the time module:
  2.  
  3. >>>import time
  4. >>>print time.__dict__
  5. {'ctime': <built-in function ctime>,
  6. 'clock': <built-in function clock>,
  7. ... 'localtime': <built-in function localtime>}
  8. >>> print time.localtime()
  9. (2006, 8, 10, 14, 32, 39, 3, 222, 1)
  10.  
  11. ## The class namespace is similar to the module namespace; however, it is created in two parts. The first part is created when the class is defined, and the second part is created when the class is instantiated. The module namespace can also be accessed using the .__dict__ attribute of the class object.
  12. Objects in the class namespace can be accessed directly using the module name and dot "." syntax. The example shows this in the print t.x and t.double() statements:
  13.  
  14. >>>class tClass(object):
  15. >>> def__init__(self, x):
  16. >>> self.x = x
  17. >>> def double(self):
  18. >>> self.x += self.x
  19. >>>t = tClass (5)
  20. >>>print t.__dict__
  21. {'x': 5}
  22. >>>print tClass.__dict__
  23. {'__module__': '__main__',
  24. 'double': <function double at 0x008D7570>, . . . }
  25. >>>print t.x
  26. 5
  27. >>>t.double()
  28. >>>print t.x
  29. 10

Report this snippet  

You need to login to post a comment.