In the last chapter, you've learned how to reuse work by defining a function in your program code. So if you want to reuse a number of functions in other programs you write the words, how should I do? As you might imagine, the answer is modules (Modules).
There are many ways to write a module, the simplest one is to create a function that contains the variables to .py
file with the extension.
Another approach is to use the Python interpreter itself is written in the local language to write modules. For example, you can use the C language to write Python module, and compiled, you can use them in your Python code by standard Python interpreter.
A program module may be further introduced into and use their functions. The same is true when we use the features of the Python standard library. First of all, we have to understand how to use the standard library modules.
Case (saved as module_using_sys.py):
import sys
print('The command line arguments are:')
for i in sys.argv:
print(i)
print('\n\nThe PYTHONPATH is', sys.path, '\n')
Output:
$ python module_using_sys.py we are arguments
The command line arguments are:
module_using_sys.py
we
are
arguments
The PYTHONPATH is ['/tmp/py',
# many entries here, not shown here
'/Library/Python/2.7/site-packages',
'/usr/local/lib/python2.7/site-packages']
First of all, we have adopted import
an import statement sys
module. Basically, this code will be translated into Python tells us that we want to use this module. sys module contains relevant Python interpreter environment and function, which is called the system functions (system).
When Python runs import sys
when this statement, it will start looking for sys
the module. In this case, because it is a built-in modules, so Python know where to find it.
If it is not a pre-compiled modules, namely modules written in Python, then the Python interpreter from its sys.path
search directory variables provided. If you find the corresponding module, the module statement will start running, and can work for you to use. It should be noted here that the initialization just in our first complete import module.
sys
Module argv
variable be indicated by using the dot, i.e. sys.argv
such forms. It clearly shows that this name is sys
part of the module. Another advantage of this approach is that this name is not any other program with you a argv
variable conflict.
sys.argv
Variable is a series string list (List) (the list will be in a later chapter shall be explained in detail). Specifically, sys.argv
it contains the command line arguments * (Command Line Arguments) * This list, which is your program using parameters passed to the command line.
If you are using an IDE to write and run these programs, look for options related to the specified command-line parameter in the program menu.
Here, when we run python module_using_sys.py we are arguments
, we pass python
to run the command module_using_sys.py
module, behind the content of the program is the parameter passed to it. Python command-line parameters are stored in sys.argv
for us to use variable.
Keep in mind here is that the name of the script running in the sys.argv
list will always be ranked first. Therefore, in this case we will have the following correspondence relationship: 'module_using_sys.py'
correspondence sys.argv[0]
, 'we'
correspondence sys.argv[1]
, 'are'
correspondence sys.argv[2]
, 'arguments'
correspondence sys.argv[3]
. To note that Python starts counting from 0 instead of 1.
sys.path
It contains a list of names in the dictionary of imported modules. You can observe sys.path
the first section of the string is empty ---- that an empty string representing the current directory is also sys.path
part of it with the PYTHONPATH
equivalent environment variable. This means that you can directly import modules located in the current directory. Otherwise, you will have to place your module in the sys.path
catalog are listed in the middle.
Also note that the current directory refers to the start of the program directory. You can run import os; print(os.getcwd())
to see what you are currently located in the program directory.
1. Press .pyc files compiled bytecode
Importing a module is a costly thing, so Python introduces some skills to enable them to more quickly complete. One way is to create byte-code compiled * (Byte-Compiled) * file, the file to .pyc
its extension, is to convert into an intermediate form of Python file. This .pyc
file is useful ---- it faster the next time you import a module from another different program, because when you import the module required part of the process has been completed. At the same time, these byte-code files are compiled independently of the operation of the platform.
Note: These .pyc
files are usually created in the corresponding .py
directory files are located. If Python do not have permission to operate to write files to this directory, .pyc
the file will not be created.
2. from..import
Statement
If you want to direct argv
variables into your program (to avoid every time input sys.
), then you can use from sys import argv
to accomplish this statement.
Warning : In general, you should try to avoid using
from...import
statements, try to use theimport
statement. This is to avoid name conflicts in your program, but also to make the program easier to read.
Case:
from math import sqrt
print("Square root of 16 is", sqrt(16))
Output:
4.0
3. Module __name__
Each module has a name, and the name of the module statement in which they are located module can be found. This is greatly useful for determining module operate independently or be introduced into this specific purpose is to come running. As previously mentioned, when the module is first introduced, it contains the code to be executed. We can make the module by running this feature in different ways, depending on whether it is for their own use or imported from other modules come in from. This module can be used __name__
to achieve the properties.
Case (save as module_using_name.py
):
if __name__ == '__main__':
print('This program is being run by itself')
else:
print('I am being imported from another module')
Output:
$ python module_using_name.py
This program is being run by itself
$ python
>>> import module_using_name
I am being imported from another module
>>>
Each Python module defines its __name__
properties. If it's the __main__
same attribute represents the module is run by a user independent, so we can take appropriate action.
4. Write your own modules
Write your own modules is very simple, this is in fact what you have been doing! This is because every Python program is also a module. You just need to make sure it .py
is the extension name. The following case will make a clear explanation.
Case (save as mymodule.py
):
def say_hi():
print('Hi, this is mymodule speaking.')
__version__ = '0.1'
Presented above is a simple module. As you can see, compared to the Python program we generally used does not provide any special distinction. Then we will see how to use this module in other Python programs.
Remember that the module should be placed under the same procedure with the other we are about to import the module directory, or is placed sys.path
under one of the directories listed.
Another module (save as mymodule_demo.py
):
import mymodule
mymodule.say_hi()
print('Version', mymodule.__version__)
Output:
$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
You will notice that we use the same access point identifier to the members of the module. Python makes good reuse the symbols, which is full of "Pythonic" type of atmosphere, which allows us to not have to learn new ways to accomplish the same thing.
Here is a use from...import
template syntax (save as mymodule_demo2.py
):
from mymodule import say_hi, __version__
say_hi()
print('Version', __version__)
mymodule_demo2.py
Content and output mymodule_demo.py
the content of the output is the same.
It should be noted here that, if introduced into mymodule
the module already exists __version__
in this name, it would be a conflict. This may be because each module usually use this name to declare their respective version number. Therefore, we recommend the best to use most of the import
statements, although this will make your program becomes a little longer.
You can also use:
from mymodule import *
This will import as say_hi
all common names, etc., but does not import the __version__
name, because the latter begin with a double underscore.
Warning: Remember that you should avoid import this form, that is
from mymodule import
.
5. dir
Functions
Built-in dir()
functions returns a list of names can be defined by the object. If the object is a module, then the list will include functions, variables within the class defined function.
The function accepts parameters. If the argument is the name of the module, the function returns a list of names of the specified module. If no argument, the function returns a list of the current module name.
Case:
$ python
>>> import sys
# 给出 sys 模块中的属性名称
>>> dir(sys)
['__displayhook__', '__doc__',
'argv', 'builtin_module_names',
'version', 'version_info']
# 此处只展示部分条目
# 给出当前模块的属性名称
>>> dir()
['__builtins__', '__doc__',
'__name__', '__package__','sys']
# 创建一个新的变量 'a'
>>> a = 5
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a']
# 删除或移除一个名称
>>> del a
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
First of all we see is dir
being imported sys
usage on the module. We can see a huge list of attributes it contains.
Then, we do not pass parameters in the form of dir
function. By default, it will return a list of attributes for the current module. To notice that the list of imported modules is also part of this list.
To observe the dir
operation of the function, we define a new variable a
and assign it a value and then check the dir
results returned, we can find the list of the same name appears in a new value. We del
removed a variable or attribute statement, this change is reflected again in the dir
function of the content is located.
About del
a little hint ---- This statement is used to delete a variable name or, when this statement is run, in this case, that is del a
, you will no longer be able to access the variable a
---- it like you've never there is too general.
To note that the dir()
function can be of any work objects. Such as running dir(str)
can access str
attribute (String, String) class.
At the same time, there is a vars () function can also return to your property values, but only possible, it can not work properly for all classes.
6. Package
Now, you must begin to comply with the hierarchy to organize your program. Variable, usually within functions, global variables function normally located inside the module. If you want to organize these modules, then how should we do? This is the package (Packages) time to be on stage.
It refers to a package comprising a module with a special __init__.py
file folder, which indicates that the folder to the Python is special because it contains Python modules.
Let us imagine: you want to create a package called "world", and which also contains a "asia", "africa" and other sub-package, while these sub packages are included, such as "india", "madagascar" modules .
Here is the structure you will build a folder:
- <some folder present in the sys.path>/
- world/
- __init__.py
- asia/
- __init__.py
- india/
- __init__.py
- foo.py
- africa/
- __init__.py
- madagascar/
- __init__.py
- bar.py
A package can be conveniently organized layered module. You will be in the standard library to see about this in many instances.
to sum up
Function as a program like that in the reusable portion, the reusable module is a program. Package is organized hierarchically to another module. Python is included with the standard library is an example of a group of related packets with the module.
We already know how to use these modules and create your own modules.
Next, we will learn some interesting concepts, they are called data structures.