Python Advanced Module

Source: Internet
Author: User
Tags integer division pow sin

In the development of computer programs, as the program code more and more, in a file code will be more and more long, more and more difficult to maintain.

In order to write maintainable code, we grouped many functions into separate files so that each file contained relatively few code, and many programming languages used this way of organizing code. In Python, a. py file is called a module.

What are the benefits of using modules?

The greatest benefit is that the maintainability of the code is greatly improved. Second, writing code does not have to start from scratch. When a module is written, it can be referenced elsewhere. When we write programs, we often refer to other modules, including Python built-in modules and modules from third parties.

The use of modules also avoids conflicting function names and variable names. Functions and variables of the same name can exist in different modules individually, so we do not have to think about names that conflict with other modules when we write our own modules. But also be aware that try not to conflict with the built-in function name. Click here to see all of Python's built-in functions.

You may also think, what if different people write the same module name? To avoid module name collisions, Python introduces a way to organize modules by directory, called packages.

For example, a abc.py file is a named abc module, and a xyz.py file is a named xyz module.

Now, assuming that our abc and xyz these two module names conflict with the other modules, we can organize the modules through the package to avoid conflicts. The method is to select a top-level package name, for example mycompany , to be stored in the following directory:

mycompany├─ __init__.py├─ abc.py└─ xyz.py

Once the package is introduced, all modules will not conflict with others as long as the package name in the top layer does not conflict with others. Now, the name of the abc.py module becomes mycompany.abc , similarly, xyz.py the module name becomes mycompany.xyz .

Please note that each package directory will have a __init__.py file that must exist, otherwise Python will use this directory as a normal directory, not a package. __init__.py It can be an empty file, or it can have Python code, because __init__.py it is a module, and its module name is mycompany .

Similarly, there can be multi -level catalogs, which form a multi-level package structure. For example, the following directory structure:

mycompany ├─ web │  ├─ __init__.py │  ├─ utils.py │  └─ www.py ├─ __init__.py ├─ abc.py └─ xyz.py

The module name of the file is the www.py mycompany.web.www module name of the two files, utils.py respectively mycompany.utils mycompany.web.utils .

when you create a module, you should be careful about naming it and not conflict with the module name that comes with Python. For example, the system comes with the SYS module, its own module is not named sys.py, otherwise it will not be able to import the system's own SYS module.

mycompany.webis also a module, the corresponding. py file for the module is __init__.py.

Summarize

A module is a set of Python code that can be used by other modules or by other modules.

When creating your own module, be aware of:

    • Module name to follow the Python variable naming specification, do not use Chinese, special characters;
    • The module name does not conflict with the system module name, it is best to see if the system already exists the module, the check method is executed in the Python interactive environment import abc , if successful, it indicates that the system exists this module.

Python's Import module

To use a module, we must first import the module. Python imports a module using the import statement. For example, import the module that comes with the system, math:

Import Math

You can think of math as a variable that points to the imported module, where we can access all the exposed functions, variables, and classes defined in the Math module:

# POW is a function . # pi is a variable 3.141592653589793

If we only want to import some of the functions of the math module used, instead of all the functions, you can use the following statement:

 from import pow, sin, log

In this way, the 3 functions of pow, sin, and log can be referenced directly, but other functions of math are not imported:

>>> Pow (2, ten)1024.0>>> sin (3.14)0.0015926529164868282

What if I encounter a name conflict? For example, the Math module has a log function, logging module also has a log function, if used simultaneously, how to resolve the name conflict?

If you import the module name using import, there is no conflict because the function name must be referenced through the module name:

Import Math, logging print math.log   #  call is Math's log function 'something')   # The logging log function is called .

If you use From...import to import the log function, it is bound to cause conflicts. At this point, you can give the function an "alias" to avoid the conflict:

 from Import Log  from Import log as Logger   #  logging log now becomes loggerprint log    I 'm calling the log of math. ' Import from Logging ')   # The logging log is called .

Dynamic Import module in Python

If the imported module does not exist, the Python interpreter will report a importerror error:

Import Somethingtraceback (most recent):   " <stdin> "  in <module>importerror:no module named something

Sometimes, two different modules provide the same functionality, such as Stringio and Cstringio, which provide Stringio.

This is because Python is a dynamic language that interprets execution, so Python code runs slowly.

If you want to improve the speed of Python code, the simplest way is to rewrite some key functions in C, which can greatly improve the execution speed.

The same functionality, Stringio is written in pure Python code, while the Cstringio part of the function is written in C, so Cstringio runs faster.

With Importerror errors, we often import modules dynamically in Python:

Try :      from Import Stringio except importerror:      from Import Stringio

The above code attempts to import from Cstringio first, and if it fails (for example, Cstringio is not installed), try importing from Stringio. This way, if the Cstringio module is present, we will get a faster run, and if Cstringio does not exist, the code will run slower, but it will not affect the normal execution of the code.

The action of the try is to catch the error and execute the except statement when the specified error is caught.

Example:

Using import ... as ..., you can also dynamically import modules of different names.

The Python 2.6/2.7 provides a JSON module, but Python 2.5 and earlier do not have JSON modules, but you can install a Simplejson module that provides the same function signatures and functions as the two modules.

Try to write the code to import the JSON module, which will work correctly in Python 2.5/2.6/2.7.

Try :     Import JSON except importerror:     Import Simplejson as JSON Print json.dumps ({'python': 2.7})

Note:

JSON (JavaScript Object Notation): A lightweight data interchange format that is easier to read and write than XML, easy to parse and generate, JSON is Python's JSON module serialization and deserialization process is Encoding and decoding

Encoding: Converts a Python object encoding into a JSON string
Decoding: Converting JSON format string decoding to Python object
For simple data types (string, Unicode, int, float, list, tuple, dict), they can be processed directly.

The Json.dumps method is encoding for simple data types.

Python's use __future__

Note: As in __name__ above, the left and right are two short horizontal.

New versions of Python introduce new features, but in fact these features already exist in the previous version. To "try out" a new feature, you can do so by importing some of the features of the __future__ module.

For example, the integer division operation of Python 2.7 is still an integer:

>>> 10/33

However, Python 3.x has improved the division of integers, "/" in addition to the floating-point number, "//" is still an integer:

>>> 10/33.3333333333333335>>> 10//33

To introduce the 3.x division rule in Python 2.7, import the __FUTURE__ division:

 from __future__ Import Division Print 10/33.3333333333333335

When an attribute of the new version is incompatible with the old version, the feature will be added to the __future__ in the old version so that the old code can test the new feature in the old version.

Example:

In Python 3.x, string unification is Unicode, no prefix u is required, and str stored in bytes must be prefixed with B. Use __future__ 's unicode_literals to write Unicode strings in Python 2.7.

Using the From __future__ import unicode_literals will bring the Python 3.x Unicode rules into Python 2.7.

Reference code:

 from __future__ Import  'am I an Unicode? ' Print isinstance (S, Unicode)

Installing third-party modules

In Python, the installation of a third-party module is done through the Package management tool PIP.

If you are using Mac or Linux, install the PIP itself this step can be skipped.

If you are using Windows, please refer to the section on installing Python to make sure that the and is checked during installation pip Add python.exe to Path .

When you try to run under a command Prompt window pip , if the Windows prompt does not find a command, you can rerun Setup to add the program pip .

Note: The Python 3.x and Python 2.x may coexist on Mac or Linux, so the corresponding PIP command is pip3 .

For example, we want to install a third-party library--python The Imaging library, which is a very powerful tool library for processing images under Python. However, PIL currently only supports Python 2.7 and has not been updated for years, so PIL-based pillow project development is very active and supports the latest Python 3.

Generally speaking Third-party libraries will be registered in the official Python pypi.python.org website, to install a third-party library, you must first know the name of the library, you can search on the official website or pypi, such as pillow name is called pillow, so the installation of Pillow command is:

Pip Install Pillow

After you have waited patiently for the download and installation, you can use pillow.

This blog reference:

Web Course: Python Advanced

Liaoche Teacher's website: https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

Python Advanced Module

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.