Skip to content

Instantly share code, notes, and snippets.

@lambdamusic
Created February 7, 2013 21:27
Show Gist options
  • Save lambdamusic/4734380 to your computer and use it in GitHub Desktop.
Save lambdamusic/4734380 to your computer and use it in GitHub Desktop.
Python: Python: module and class namespaces
## 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment