[Tutor] importing

Lie Ryan lie.1296 at gmail.com
Tue Dec 22 22:29:55 CET 2009


On 12/23/2009 8:14 AM, Robert Johansson wrote:
> Hi all, suppose I need to import a module inside a class and that I need
> to use it in to different methods. Is this is the way to do it?

generally you should keep all imports at the top of the file. There are 
times when importing only to specific methods or class is useful, but in 
general keep them at top.

and in those cases where you import to inside a class, the module 
becomes a class attribute so you use self. or ClassName. to reach the 
module:

class ClassName(object):
     import random
     def foo(self):
         print self.random.random()
         print ClassName.random.random()



More information about the Tutor mailing list