[Tutor] how import a module upon instantiation of a class?

Alan Gauld alan.gauld at btinternet.com
Mon Sep 1 17:55:09 CEST 2014


On 01/09/14 15:13, Steven D'Aprano wrote:

> To make it a global name, you need the global keyword:
>
> py> def cheese():  # take two
> ...     global string
> ...     import string
> ...
> py> cheese()
> py> string
> <module 'string' from '/usr/local/lib/python2.7/string.pyc'>

And co ing back to Albert's original request this little insight made me 
try something and it seems to work...

You can assign the name inside the class, thus providing the class level 
import that Albert wanted:

 >>> class C:
...   def __init__(self):
...     import sys
...     self.__sys = sys
...   def printSys(self):
...     print self.__sys.path
...
 >>> c = C()
 >>> sys
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
 >>> c.__sys
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: C instance has no attribute '__sys'
 >>> c.printSys()
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', ...

So now you have a module imported inside a class such that it
is only visible inside objects of that class.

Now why you would want that I'm less sure, but you can do it...

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list