Return to Snippet

Revision: 21860
at December 22, 2009 15:25 by magicrebirth


Initial Code
## 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:

>>>import time
>>>print time.__dict__
{'ctime': <built-in function ctime>,
 'clock': <built-in function clock>,
 ... 'localtime': <built-in function localtime>}
>>> print time.localtime()
(2006, 8, 10, 14, 32, 39, 3, 222, 1)

## 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.
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:

>>>class tClass(object):
>>>    def__init__(self, x):
>>>        self.x = x
>>>    def double(self):
>>>        self.x += self.x
>>>t = tClass (5)
>>>print t.__dict__
{'x': 5}
>>>print tClass.__dict__
{'__module__': '__main__',
 'double': <function double at 0x008D7570>, . . . }
>>>print t.x
5
>>>t.double()
>>>print t.x
10

Initial URL

                                

Initial Description

                                

Initial Title
Python: module and class namespaces

Initial Tags
class, python, module

Initial Language
Python