Python 简明教程

Python - Packages

Python 中,模块是一个 Python 脚本,其带有 .py 扩展名,并包含类、 functions 等对象。模块化方法会进一步扩展 Packages in Python 概念。包是一个包含一个或多个模块文件的文件夹;此外,一个特殊文件 "init.py" 可能是空的,但可能包含包列表。

In Python, the module is a Python script with a .py extension and contains objects such as classes, functions, etc. Packages in Python extend the concept of the modular approach further. The package is a folder containing one or more module files; additionally, a special file "init.py" file may be empty but may contain the package list.

Create a Python Package

让我们创建一个名称为 mypackagePython package 。请按照以下步骤进行操作:

Let us create a Python package with the name mypackage. Follow the steps given below −

  1. Create an outer folder to hold the contents of mypackage. Let its name be packagedemo.

  2. Inside it, create another folder mypackage. This will be the Python package we are going to construct. Two Python modules areafunctions.py and mathfunctions.py will be created inside mypackage.

  3. Create an empty ".init.py" file inside mypackage folder.

  4. Inside the outer folder, we shall later store a Python script example.py to test our package.

file/folder structure 应如下所示:

The file/folder structure should be as shown below −

folder structure

使用您喜爱的代码编辑器,将以下两个 Python modules 保存至 mypackage 文件夹中。

Using your favorite code editor, save the following two Python modules in mypackage folder.

Example to Create a Python Package

# mathfunctions.py
def sum(x,y):
   val = x+y
   return val

def average(x,y):
   val = (x+y)/2
   return val

def power(x,y):
   val = x**y
   return val

创建另一个 Python 脚本:

Create another Python script −

# areafunctions.py
def rectangle(w,h):
   area = w*h
   return area

def circle(r):
   import math
   area = math.pi*math.pow(r,2)
   return area

现在,让我们使用此包文件夹之上的 Python 脚本来测试 myexample 包。请参阅以上文件夹结构。

Let us now test the myexample package with the help of a Python script above this package folder. Refer to the folder structure above.

#example.py
from mypackage.areafunctions import rectangle
print ("Area :", rectangle(10,20))

from mypackage.mathsfunctions import average
print ("average:", average(10,20))

此程序从 mypackage 导入功能。如果执行以上脚本,您应该获得以下 output

This program imports functions from mypackage. If the above script is executed, you should get following output

Area : 200
average: 15.0

Define Package List

您可以将包中的选定功能或任何其他资源放置到“ init .py”文件中。让我们将以下代码放入其中。

You can put selected functions or any other resources from the package in the "init.py" file. Let us put the following code in it.

from .areafunctions import circle
from .mathsfunctions import sum, power

要从该包中导入可用功能,请将以下脚本保存为 testpackage.py,该脚本位于包文件夹的上方,同前。

To import the available functions from this package, save the following script as testpackage.py, above the package folder as before.

Example to Define a Package List

#testpackage.py
from mypackage import power, circle

print ("Area of circle:", circle(5))
print ("10 raised to 2:", power(10,2))

它将生成以下 output

It will produce the following output

Area of circle: 78.53981633974483
10 raised to 2: 100

Package Installation

目前,我们只能从包文件夹上方的脚本访问包资源。若要在文件系统中的任何位置使用包,您需要使用 PIP 实用程序对其进行安装。

Right now, we are able to access the package resources from a script just above the package folder. To be able to use the package anywhere in the file system, you need to install it using the PIP utility.

首先,将以下脚本保存到父文件夹中,它位于包文件夹的级别上。

First of all, save the following script in the parent folder, at the level of package folder.

#setup.py
from setuptools import setup
setup(name='mypackage',
version='0.1',
description='Package setup script',
url='#',
author='anonymous',
author_email='test@gmail.com',
license='MIT',
packages=['mypackage'],
zip_safe=False)

在保持父文件夹状态的同时,运行命令提示符中的 PIP 实用程序。

Run the PIP utility from command prompt, while remaining in the parent folder.

C:\Users\user\packagedemo>pip3 install .
Processing c:\users\user\packagedemo
 Preparing metadata (setup.py) ... done
Installing collected packages: mypackage
 Running setup.py install for mypackage ... done
Successfully installed mypackage-0.1

您现在应该能够在任何环境中导入 package 的内容了。

You should now be able to import the contents of the package in any environment.

C:\Users>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mypackage
>>> mypackage.circle(5)
78.53981633974483