Python-Ref > Basic usage > Modules > Writing modules
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Writing modules

How to create your own modules.
If you have ever written any python code into a file you have in fact already created a module, albeit unwittingly.
Every python file is also a module that can be imported from another python program. The following example shows a very simple case of this.
Expand/Shrink
  1   def hello():
  2       return "Hello, I am a module."
Zdroj: (modules2.1.py)
  1   import module21
  2   
  3   print module21
  4   print module21.hello()
stdout:
<module 'module21' from '/mnt/bkchem.img/projects/python-ref/_tmp/module21.py'>
Hello, I am a module.
Doba běhu: 22.2 ms
The one thing that usually distinguishes modules from other python scripts is the absence of the main body of the program. That is, module defines functions and classes but does not do enything when run by itself. The reason for this is that any such code would be executed when the module is imported. How to write a module that is also a program on itself is shown on the page Modules that act as programs.
Expand/Shrink
  1   def hello():
  2       return "Hello, I am a module."
  3   
  4   print "This is part of the body of the file."
  5   print range( 10)
Zdroj: (modules2.2.py)
  1   print "-- before import"
  2   import module22
  3   print "-- after import"
  4   print module22.hello()
stdout:
-- before import
This is part of the body of the file.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-- after import
Hello, I am a module.
Doba běhu: 21.5 ms