简体   繁体   English

我该如何导入该功能?

[英]How can I import the function?

I have a Python function in a file called func.py 我在一个名为func.py的文件中有一个Python函数

def calc(x,y):
    return x*y

I have to import this function while working in another file called mytask.py 我必须在另一个名为mytask.py的文件中导入此函数

How can I import the function? 我该如何导入该功能?

Save the file in the same directory and then have a statement 将文件保存在同一目录中,然后生成一个语句

from func import calc

To import from a different directory 从其他目录导入

  1. Add the file to a new directory, call it funcs 将文件添加到新目录,将其命名为funcs
  2. Create a file __init__.py and have a line __all__ = ['calc'] 创建一个文件__init__.py并有一行__all__ = ['calc']
  3. Import as from funcs import func from funcs import func

Reference 参考

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

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