Python study Note 5: module and package, python study note Module
I. import modules using import
Cal. py:
#! /Usr/bin/pythondef add (x, y): return x + yif _ name _ = '_ main _': print add (1, 2)
Note: __name _ is a built-in variable. If the call value in CLI is _ mail __, otherwise it is a file name.
Import in new. py:
Import calprint cal. add (2, 3 );
Ii. Package: modules organized by directory name
1. Create a folder named "package name"
2. Create a _ init _. py file in the folder.
3. Store script files, compiled extensions, and sub-packages in this folder as needed
4. import pack. m1, pack. m2, and pack. m3 in the file.
5. Use pack. m1.xxx to call the module method in the package.
Sample directory structure:
Util/── cal. py ── cal. pyc ├ ── _ init _. py ── _ init _. pyc
Call example new. py:
Import util. calprint util. cal. add (2, 3); // 5
Or use the alias:
Import util. cal as cprint c. add (2, 3); // 5
You can also use the from statement to describe it:
From util. cal import addprint add (2, 3 );