简体   繁体   English

在您自己的模块中使用来自内置模块的 function - Python

[英]Using a function from a built-in module in your own module - Python

I'm new with Python and new on Stackoverflow, so please let me know if this question should be posted somewhere else or you need any other info:).我是 Python 和 Stackoverflow 上的新手,所以请让我知道这个问题是否应该发布在其他地方或者您需要任何其他信息:)。 But I hope someone can help me out with what seems to be a rather simple mistake...但我希望有人可以帮助我解决一个看似相当简单的错误......

I'm working with Python in Jupyter Notebook and am trying to create my own module with some selfmade functions/loops that I often use.我正在 Jupyter Notebook 中使用 Python 并尝试使用我经常使用的一些自制函数/循环创建自己的模块。 However, when I try to some of the functions from my module, I get an error related to the import of the built-in module that is used in my own module.但是,当我尝试使用我的模块中的某些功能时,我收到与导入我自己的模块中使用的内置模块相关的错误。

The way I created my own module was by:我创建自己的模块的方式是:

  1. creating different blocks of code in a notebook and downloading it as 'Functions.py' file.在笔记本中创建不同的代码块并将其下载为“Functions.py”文件。
  2. saving this Functions.py file in the folder that i'm currently working in (with another notebook file)将此Functions.py文件保存在我当前正在使用的文件夹中(使用另一个笔记本文件)
  3. in my current notebook file (where i'm doing my analysis), I import my module with ' import Functions' .在我当前的笔记本文件(我正在分析的地方)中,我使用 ' import Functions'导入我的模块。

So far, the import of my own module seems to work.到目前为止,我自己的模块的导入似乎有效。 However, some of my self-made functions use functions from built-in modules.但是,我的一些自制函数使用了内置模块中的函数。 Eg my plot_lines() function uses math.ceil() somewhere in the code.例如,我的plot_lines() function 在代码的某处使用了 math.ceil() Therefore, I imported 'math' in my analysis notebook as well.因此,我也在我的分析笔记本中导入了“数学”。 But when I try to run the function plot_lines() in my notebook, I get the error "NameError: name 'math' is not defined" .但是,当我尝试在笔记本中运行 function plot_lines() 时,出现错误"NameError: name 'math' is not defined"

I tried to solve this error by adding the code 'import math' to the function in my module as well, but this did not resolve the issue.我也尝试通过将代码“导入数学”添加到我的模块中的 function 来解决此错误,但这并没有解决问题。

So my question is : how can I use functions from built-in Python modules in my own modules?所以我的问题是:如何在我自己的模块中使用内置 Python 模块的功能?

Thanks so much in advance for any help!非常感谢您的帮助!

If anyone encounters the same issue: add 'import math' to your own module.如果有人遇到同样的问题:将“导入数学”添加到您自己的模块中。

Make sure that you actually reload your adjusted module, eg by restarting your kernell!确保您确实重新加载了调整后的模块,例如通过重新启动您的内核!

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

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