Home > Backend Development > Python Tutorial > What is the package in python? what's the effect? Introduction to packages in python

What is the package in python? what's the effect? Introduction to packages in python

不言
Release: 2018-11-20 16:10:57
forward
7546 people have browsed it

This article brings you what is the package in python? what's the effect? The introduction of packages in python has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is a package?

Package is a way to organize the python module name space through ".module name". We wear Each folder can be called a package.

But please note that it is specified in python2. The __init__.py file must exist in the package.

The purpose of creating a package is not to run, but to be imported and used. A package is just a form, and the essence of a package is a module.

2. What is the function of a package?

It is essentially a folder, so the only function of a folder is to organize files. As more and more functions are written, we cannot put

all the functions in one folder, so we use modules to Organization function, as there are more and more modules, we need to use folders to organize module files to improve the structure and maintainability of the program.

Next Create some packages for later learning. Packages are easy to create. You only need a folder with __init__.py.

import os
os.makedirs('glance/api')
os.makedirs('glance/cmd')
os.makedirs('glance/db')
l = []
l.append(open('glance/__init__.py','w'))
l.append(open('glance/api/__init__.py','w'))
l.append(open('glance/api/policy.py','w'))
l.append(open('glance/api/versions.py','w'))
l.append(open('glance/cmd/__init__.py','w'))
l.append(open('glance/cmd/manage.py','w'))
l.append(open('glance/db/__init__.py','w'))
l.append(open('glance/db/models.py','w'))
map(lambda f:f.close() ,l)
Copy after login

Create the directory structure

We add some methods to each folder:

#policy.py
def get():
    print('from policy.py')
    
#versions.py
def create_resource(conf):
    print('from version.py: ',conf)
    
#manage.py
def main():
    print('from manage.py')
    
#models.py
def register_models(engine):
    print('from models.py: ',engine)
Copy after login

We can use the contents of the package in test.py, and when we import the package, we can use import or from xxx The form of import xxx

import glance.db.models
glance.db.models.register_models('mysql')
from glance.api.policy import get
get()
Copy after login

However, note: in the form of from xxx import xxx, "dot" cannot appear after the import. That is to say, from a.b import c is OK.

But from a import b.c is wrong

3.What does __init__.py do?

No matter which method we use to import a package, as long as it is the first time it is imported The package or any other part of the package will first execute the __init__.py file.

This file can be empty, but it can also store some initialization code.

Then we used before Can from xxx import * be used for package calls?

Yes, we need to give __all__ in the __init__.py file to determine the * imported content.

print("我是glance的__init__.py⽂件. ")
x = 10
def hehe():
    print("我是呵呵")
    
def haha():
    print("我是哈哈")
__all__ = ['x', "hehe"]
Copy after login

test.py

from glance import *
print(x) # OK
hehe() # OK
haha() # 报错. __all__⾥没有这个⻤东⻄
Copy after login

4. Relative import and absolute import

Our final package glance is written for others to use, and there will also be mutual imports within the glance package. At this time, there are two import methods: absolute import and relative import.

1). Absolute import: glance as the starting point

2). Relative import: use. Or. . As a starting point

For example, we use glance/cmd/manage.py in glance/api/version.py

# 在glance/api/version.py
#绝对导⼊
from glance.cmd import manage
manage.main()
#相对导⼊
# 这种情形不可以在versions中启动程序.
# attempted relative import beyond top-level package
from ..cmd import manage
manage.main()
Copy after login

We should pay attention when testing, the python package path is the same as The directory where the running script is located is related.

In python, the program you run is not allowed to exceed the scope of the current package (relative import).

If you use absolute import, there is no such problem. .That is, if you use relative import in the package, then when using the information in the package, you can only import it outside the package

# 在policy.py
import versions
Copy after login

If the entry of our program is policy, Then there is no problem with the program at this time. But if we import the policy in glance outside glance, an error will be reported.

The reason is that if we access it from outside When setting policy, the path in .sys.path is outside. Therefore, the versions module cannot be found directly. Therefore, an error will definitely be reported:

ModuleNotFoundError: No module named 'versions'
Copy after login
When we make an error in importing the package, we must First look at sys.path. See if you can really get the package information.

5. Import a package separately

# 在test.py中
import glance
Copy after login

The imported glance cannot do anything at this time. Because in glance There is no loading of sub-packages in __init__.py. At this time, we need to introduce the contents of the sub-packages in __init__.py respectively.

1. Use relative paths

2. Notes on using absolute paths to

packages:

The import statements related to packages are also import and from xxx import xxx, but no matter which one is used, no matter where it is , one principle must be followed when importing: For any import with a dot, the left side of the

dot must be a package. Otherwise, an error will be reported. You can bring a series of dots. For example: from a.b.c import d

The above is the detailed content of What is the package in python? what's the effect? Introduction to packages in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template