Python core technology and real - No.11 | modular program

  We now have summarized Python's basic moves and routines, you can now write some not-so-simple systematic project or a large amount of code of the application. At this time, a simple .py files will become too bloated, unable to bear a heavy responsibility heavyweight software development. This requires the contents of this chapter - to simplify, it will feature a modular, documented , and thus can be like building blocks, different functions, build up in the formation of large-scale projects.

Simple Modular

  The easiest modular approach is to split the functions, classes, constants to different files, put them in the same folder, and then use the following statement to import

from filename import function_name
from filename import class_name

To give an example

#utils.py

def get_sum(a,b):
    return a+b
#class_utils.py

class Encoder(object):
    def encode(self,s):
        return s[::-1]

class Decoder(object):
    def decode(self,s):
        return ''.join(reversed(list(s)))
#main.py

from utils import get_sum
from class_utils import *
print(get_sum(2, 3))

encoder = Encoder()
decoder = Decoder()

print(encoder.encode('abc'))
print(decoder.decode('dcba'))

We function get_sum () in a file (utils.py), and classes in another file (class_utils.py), the main function was to direct calls, from ... import ... can put classes and functions required are introduced into the room.

But slowly, we found that all the files are placed in a folder is not good management, it is necessary to establish multi-level directory, like this

1 .
2 ├── utils
3 │   ├── utils.py
4 │   └── class_utils.py
5 ├── src
6 │   └── sub_main.py
7 └── main.py

When subdirectory module main.py call, we need to change the code

#sub_main.py

import sys
sys.path.append('..')

from utils.class_utils import *
from utils import utils as fun

print(fun.get_sum(2, 3))

encoder = Encoder()
decoder = Decoder()

print(encoder.encode('abc'))
print(decoder.decode('dcba'))

sub_main function call is a subdirectory under the parent directory, we will build this catalog ( '..') is loaded into the environment variable. The method of introduction is also different, methods, and use of the imported module can look at the article written earlier: Import of python modules .

One point to note, import the same command module is executed once, so you can prevent duplicate import module problems. In many companies the programming specification, except for some very special circumstances, import must be in the forefront of the program .

Another point, in many tutorial, we have to build a module __init__.py file in the folder where the file content may be empty, mainly used to describe package (package) module interface of external exposure. But this is Python2 specification. Python3 in future versions, __ init__.py not required.

Modular project

  Many large projects, workspace a project team may have thousands of files, several hundred thousand to several million lines of code, call the above mentioned method has been wholly inadequate, and here we take a look at the modular organization of science

  We must first look at the concept of absolute and relative paths. We have two files in the following path

a1/b1/c1/d1/e1/example.txt
a1/b1/c1/d2/e2/example2.txt

If we jump from e1 to e2 folder, there are two ways

# Method. 1 
CD A1 / B1 / C1 / D2 / E2
 # Method 2 
../../d2/e2

Method 1 is the absolute path, and the method 2 is the relative path. Among them, with a little bit of (../) on behalf of the parent directory.

  Usually a Python file at run time, there will be a run-time position, the beginning of this file is the file resides. The following statement can change the position of the current Python interpreter. And this method is not recommended. Because a large-scale project to determine the path is very necessary .

import sys
sys.path.append('..')

  First, because the code may migrate relative to hi will make the reconstruction only unsightly, but also prone to error. Therefore, as an absolute position in the large-scale project is the first prerequisite. For a separate project, to pursue all manner of modules, it is best to start from the root directory of the project traceability , which is called relative, absolute path. Let's create a new project, the structure of the project are as follows:

1 .
2 ├── proto
3 │   ├── mat.py
4 ├── utils
5 │   └── mat_mul.py
6 └── src
7     └── main.py
#proto/mat.py

class Matrix(object):
    def __init__(self,data):
        self.data = data
        self.n = len(data)
        self.m = len(data[0])
#utils/mat_mul.py

from proto.mat import Matrix

def mat_mul(matrix_1:Matrix,matrix_2:Matrix):
    assert matrix_1.m == matrix_2.n
    n,m,s = matrix_1.n,matrix_1.m,matrix_2.m
    result = [[0 for _ in range(n)] for _ in range(s)]
    for i in range(n):
        for j in range(s):
            for k in range(m):
                result[i][k] += matrix_1.data[i][j] * matrix_2.data[j][k]

    return Matrix(result)
#src/main.py

from proto.mat import Matrix
from utils.mat_mul import mat_mul

a = Matrix([[1,2],[3,4]])
b = Matrix([[5,6],[7,8]])

print(mat_mul(a,b).data)

##########输出##########
[[19, 22], [43, 50]]

Examples of this case and in front of the like, but because of the use by importing pycharm build projects directly proto.mat import, the different files in different sub-folder, cross-module calls are searching directly from the top. It must be a new project, you can not create a new folder in the project has been built in.

But when we use the command line to call the src folder under the folder Executive

python main.py

##########输出##########
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from proto.mat import Matrix
ModuleNotFoundError: No module named 'proto'

The wrong bar! Because the Python interpreter in the face of import, he will look for modules in a particular list, we can look at this list

import sys

print(sys.path)

Pycharm fine lesson plans in the project is that the root directory is set to list in one (I will not list too long to show up). So when we run main.py, import will look for the appropriate package from the root directory.

How to do that ordinary Python runtime environment?

The first: to a miracle - forced to modify sys.path list. The root directory directly added to the list

Import SYS 
sys.path.append (R & lt ' root path ' )

So our import would be a straightforward task. But the absolute path in the code itself is a very recommended way (written in the configuration file will be because of configuration files need to find a path, so he entered a cycle of death)

The second method: Modify PYTHONHOME. Python can mention here the Virtual Environment, Python can be very handy tool Virtualenv a new common Python runtime environment. In fact, every Python project, it is best to have a separate runtime environment to maintain the purity of packages and modules.

In a virtual environment, you can find a file called active, at the end of this document, you can add the following content

the PYTHONPATH = Export ' project path'

So that each will automatically be added by activating the active runtime environment when the project root directory to the search path to go.

Magic if __name__ == '__main__'

Finally, we look at a very common wording:

if __name__ == '__main__':

This syntax what use is it? Python script preload, and C ++, Ja biggest difference is not required to provide a dominant main () function entry.

But we are in the process of importing files, put all exposed code execution all over again. But most of the time we do not want them executed, the code at this time if we want to put something packaged as a module, and wanted him to perform only when needed, then put on the need to perform if __name__ == '__main__' inside. Because __name__ is a built-in parameters, we use import to import the time, __ name__ will be assigned the name of the module is, of course, is not equal to '__main__' up!

Questions

 We have two ways when import

# Mode A 
from module_name Import *
 # mode B 
Import module_name

When the normal use of which is more suitable for it?

All modules will import under the first program path, lies the problem: If you have the same name or other functions and modules imported class names, can easily lead to conflict.

The second use of the time you need to call in the following manner. The equivalent of adding a layer of layer, can effectively avoid conflict because of the same name caused.

model_name.fun()

 

Guess you like

Origin www.cnblogs.com/yinsedeyinse/p/11317124.html