Python reference module and find module path

Source: Internet
Author: User
Tags java reference

# This article mainly describes the Python reference module and Python lookup module path of the relevant information, the need for friends can refer to the following

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-*- ID = 1"This person"print  namedef 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:

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>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.>>>Importpersonthis Person>>> Person.say ("Hello") This person says hello>>>PrintPerson.namethis 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-*- ID = 2"Thispet"print  namedef 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

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#

modify person.py, direct reference to Anmial package:

 #  -*-coding:utf-8-*- ID = 1name  =  " this person    " print   Name  def   Say (something):  print  name, " says   "   Import   animal  def  " have ():  print  name,  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>>>

About the Python reference module and Python find the module path of knowledge, to introduce so many, I hope to help you!

Python reference module and find module path

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.