简体   繁体   English

如何从Python包中导入模块

[英]How to import a module from a package in Python

I'm quite new to Python und programming in general and have a bit of a problem with packages. 一般而言,我对Python und编程还是相当陌生的,对于程序包有一些问题。

I made a directory called Package_Test and created a file named Test package in it called FUNCTIONS . 我创建了一个名为Package_Test的目录,并在其中创建了一个名为Test package的文件,名为FUNCTIONS

This package contains the init file and a file add . 该软件包包含init文件和add文件。 add contains a function, also called add that returns the sum of two given numbers. add包含一个函数,也称为add ,它返回两个给定数字的和。

The directory tree looks as follows: 目录树如下所示:

Package_Test Package_Test

Test 测试

FUNCTIONS 职能

init 在里面

add

I want to use the add function from the package in the file Test and tried the code below, but always get the error 我想使用文件Test中的包中的add函数并尝试了下面的代码,但始终会收到错误

Traceback (most recent call last): File "D:/CLRS_Codes/PACKAGE_TEST/Test.py", line 1, in import FUNCTIONS File "D:\\CLRS_Codes\\PACKAGE_TEST\\FUNCTIONS__init__.py", line 2, in from add import add ModuleNotFoundError: No module named 'add' 追溯(最近一次通话最近):导入功能中的文件“ D:/CLRS_Codes/PACKAGE_TEST/Test.py”,第1行,文件“ D:\\ CLRS_Codes \\ PACKAGE_TEST \\ FUNCTIONS__init __。py”,从添加导入添加ModuleNotFoundError:没有名为“添加”的模块

In the add file I wrote: 在添加文件中,我写道:

def add(x, y):

    return x + y

In the init file I wrote: 初始化文件中,我写道:

from add import add

In the Test-file I wrote: 在测试文件中,我写道:

import FUNCTIONS

print(add(4,2))

I attached a picture to make the whole thing clearer. 我附上一张图片,使整个内容更加清晰。

I would be deeply thankful for any help. 感谢您的帮助。

The Test-file 测试文件

You can use import FUNCTIONS.add.add as add or from FUNCTIONS.add import add . 您可以使用import FUNCTIONS.add.add as add也可以from FUNCTIONS.add import add Both of these methods allow you to reference the add function by it's full name each time. 这两种方法都允许您每次以全名引用add函数。

First off, empty the __init__.py file. 首先,清空__init__.py文件。

Then in the Test.py change "import FUNCTIONS" to either: 然后在Test.py中将“ import FUNCTIONS”更改为:

  1. import FUNCTIONS.add 导入FUNCTIONS.add
    • This'll mean you need to call any function from that file as "FUNCTIONS.add.function_name(arguments)" 这意味着您需要以“ FUNCTIONS.add.function_name(arguments)”的形式调用该文件中的任何函数
    • eg the add function in your example will be called through "FUNCTIONS.add.add(number1, number2)" 例如,您示例中的add函数将通过“ FUNCTIONS.add.add(number1,number2)”进行调用
  2. from FUNCTIONS.add import * 从FUNCTIONS.add导入*
    • This'll allow you to call any functions from that file as "function_name(arguments) 这将允许您以“ function_name(参数)”的形式调用该文件中的任何函数
    • eg the add function in your example will be called through "add(number1, number2)" 例如,您示例中的add函数将通过“ add(number1,number2)”进行调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM