The mutual independent reference between modules is the basic ability of any programming language. The word "module" may be different in various programming languages, but we can simply assume that a program file is a module that contains the definition of a class or method. For compiled languages, such as C # A. cs file in Java, A. java or compiled. class file can be thought of as a module (but often not as a module); It is more intuitive for interpreted languages, such as PHP. php files, which in Python are. py files can be considered a module. There are "packages" on the "module", primarily to facilitate the organization and management of modules. such as C # The compiled. dll file (but is often not described as a package, but a library), Java will be the. class packaged. jar file, PHP. Phar file (mimicking the Java package), a specially defined folder in Python is a package that can be packaged as an egg file. But for the interpretive language "package" is not compiled into a low-level language and then packaged meaning, it is more convenient to modular and management of the dependencies between modules. Each programming language has certain conventions for module and package management, and without understanding these conventions, it can be a hindrance to learning this language. Now I'd like to comb through these conventions of python.
One, the path of the Python lookup module
To run a Python app or reference a Python module, the Python interpreter has a lookup process. You can add a search path to Python by setting an environment variable Pythonpath to make it easier to find the relevant Python module (the settings for different operating system environment variables are slightly different, and the following are the Windows environments by default). This is the same as many applications need to set a system environment variable. The command line can be set by the following command:
C:\users\administrator>set pythonpath=e:/project/python/moduleandpackage/
After entering the Python environment, you can get the configuration of the current search path through the Python's Sys.path property, and you can see that the path we set previously is already in the current search path.
C:\users\administrator>Pythonpython2.7.11 (v2.7.11:6d1b6a68f775, Dec 5, 20:32:19) [MSC v.1500 32bit (Intel)] on Win32type" Help","Copyright","credits" or "License" forMore information.>>>ImportSYS>>>sys.path["','E:\\project\\python\\moduleandpackage','C:\\windows\\system32\\python27.zip','C:\\python\\dlls','C:\\python\\lib','C:\\python\\lib\\plat-win','C:\\PYTHON\\LIB\\LIB-TK','C:\\python','c:\\python\\lib\\site-packages']>>>
The Append method of the Sys module can also be used to increase the search path in the python environment.
>>> Sys.path.append ("E:\\project\\python\\moduleandpackage2")>>>sys.path["','E:\\project\\python\\moduleandpackage','C:\\windows\\system32\\python27.zip','C:\\python\\dlls','C:\\python\\lib','C:\\python\\lib\\plat-win','C:\\PYTHON\\LIB\\LIB-TK','C:\\python','c:\\python\\lib\\site-packages','E:\\project\\python\\moduleandpackage2']>>>
II. modules and packages in Python
As mentioned earlier, each. py file can be thought of as a Python module, and the. py file can contain classes, methods, variables, and constants (Python has no strict constants, only conventions with uppercase variables as constants). It is also possible to write all logical statements directly in the file and execute them directly from the top under load, similar to other interpreted languages. For example, we chose to create a text file in the folder Moduleandpackage. person.py file creates a simple Python module with the following contents:
# -*-coding:utf-8-*- = 1= "This person"print name
def say (something): print name,'says', something
Then we can execute the person.py in the Python environment. We can execute person.py directly like executing a batch file and enter it on the cmd command line:
Python e:/project/python/moduleandpackage/person.py
Essentially, the entry modules for any Python application are executed (like the main function in C # and Java), but referencing a module establishes the context in which it is run. We first set up an environment variable pythonpath so that the Python interpreter can find the person.py module and then import the person module to access its methods or variables.
c:\users\administrator >pythonpython 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5, 20:32:19) [MSC v.1500 32 bit (Intel)] on WI N32type " help ", " copyright ", " Credits " or " license " for more information. >>> import personthis person
>>> Person.say ("hello") This person says helloprint Person.name
This person
>>>
Python needs to go down some fixed path to find the Python module, which we set to find in Moduleandpackage. But there are also directory levels under these paths, how does Python find the modules in subdirectories? In particular, when referring to third-party packages, we also need to know a certain level of relationship. In fact, Python constructs the package structure through directories and files, and the package is nested in layers, the same as the directory layer nesting, which constitutes the access path within the package (or namespace, or the Python application's namespace is corresponding to its directory and file structure, and seems to be missing some flexibility, but also simpler). For example, in the Moduleandpackage folder, create a folder animal, which creates a text file pet.py, with the following contents:
# -*-coding:utf-8-*- = 2= "thispet"print name
def run (somewhere): print name,'runs', somewhere
So how do you refer to the pet.py module? In accordance with Python conventions, you need to create an empty text file named __init__.py in the animal folder to identify the animal folder as a package. If there is a folder in the Animal folder as a package, you must also include the __init__.py file. This identifies the path to the access for the layer layer.
Import Animal.petthis Pet
>>>Print animal.pet.namethis pet
>>> Animal.pet.run ("everywhere")
This pet runs everywhere
>>>
Or use the FROM keyword to directly import a property or method within a module:
from Import name,run>>>Print namethis pet
>>> Run ("everywhere") This pet runs everywhere>>>
Iii. Python inter-module reference
In short, we can refer to a Python module as long as it is in the search path where it executes the environment configuration and where it is part of the package structure. A basic example of module references has been provided above. Except that the import statement is written in the module file when the module is referenced, we modify the code of the person.py module.
1, from, import and as
#-*-coding:utf-8-*-ID= 1name=" This person"Printnamedefsay (something):PrintName'says', something fromAnimal.petImportname as Pet_name, run as Pet_rundefHave ():PrintName' has', Pet_name
The import statement can be written anywhere in the document, even in an if statement, for better control of the module reference. You can also use the AS statement to reference with another variable name to avoid variable name collisions.
Import personthis personthis Pet Print person.namethis Person Print person.pet_namethis Pet>>> person.have ()This person have this pet >>>
2. * Wildcard characters
The import code above explicitly refers to the variable name, but if you want to refer to all variables in the module you can use the * wildcard character, the above import statement is rewritten as follows:
from Import *
However, this can cause variable name collisions, where the name variable conflicts, overwriting the value of the person's own name variable:
Import personthis personthis Pet Print Person.namethis Pet
However, if you want to use the * wildcard character, and do not want to refer to all the variables in the module, you can use variable __all__ in the module to limit, modify the pet.py, limit the reference ID and run two variable names.
# -*-coding:utf-8-*- __all__ = [" id Span style= "COLOR: #800000" > ", ' run " ]id = 2 Name = this pet " print name def run (somewhere): print name, " runs , Somewhere
Because the name variable in the pet module is not referenced, the value of the person's name variable is not changed, and run can be called.
Import personthis personthis Pet Print person.namethisperson >>> person.run ("Nowhere") This pet runs Nowhere>>>
3. Reference Package
The above all refer to the specific Animal.pet module, but this is a relatively independent and has a large number of modules of the package is cumbersome, can be directly import animal it? The answer is yes, but Python does not look like a C # reference DLL or Java reference jar, and the module within the package can be accessed directly through the namespace (under Access control permissions). Python still needs to import the specific modules in the package by default, but the workaround is to use the __init__.py file in the package to prepare the variables in the packages that need to be referenced in advance, similar to exposing the in-package interface to external referrers. The __init__.py file code is executed when the package or module within the package is referenced, so that some initialization work can be done in it. Modify the __init__.py file in the animal folder as follows, where the module can use an absolute path and a relative path, relative to a period in the path. Represents a sibling directory with two periods: Represents the parent directory.
Print " __init__ " from Import name as Pet_name, run as Pet_run
# From animal.pet import name as Pet_name, run as Pet_run
# From . Pet import name as Pet_name, run as Pet_run
Modify person.py to refer to the Anmial package directly:
#-*-coding:utf-8-*-ID= 1name=" This person"Printnamedefsay (something):PrintName'says', somethingImportAnimaldefHave ():PrintName' has', Pet_name
Referring to the person module in the Python environment, person references animal, and automatically executes the __INIT__ code load related variables, the Dir method allows you to view the variables in the module, where two underscores start with each module, which has a special effect, is pre-defined by Python.
>>>Importpersonthis Person__init__This pet>>>dir (person) ['ID','__builtins__','__doc__','__file__','__name__','__package__',' have', 'name','Pet','Pet_name','Pet_run','say']>>>PrintPerson.pet_namethis Pet>>> Person.pet_run ("Nowhere") This pet runs nowhere>>>
Python's module reference and lookup path