search
HomeBackend DevelopmentPython TutorialWhat is the package in python? what's the effect? Introduction to packages in python

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)

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)

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()

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"]

test.py

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

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()

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

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'
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

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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python in Action: Real-World ExamplesPython in Action: Real-World ExamplesApr 18, 2025 am 12:18 AM

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python's Main Uses: A Comprehensive OverviewPython's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AM

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool