我是Python新手,如果在编写此问题时没有使用适当的白话,我表示歉意。我在Windows机器上使用Python 3.6.1。我提供了我遇到的问题的一个工作示例。加载具有相关类的模块
假设我写了一个保存在Demo_func.py文件中的模块。它包含以下功能:
def chebyshev_nodes(degree, domain):
return Chebyshev.basis(degree,domain).roots()
我然后运行下面的脚本:如果不是我写我的脚本中的函数chebyshev_nodes
NameError: name 'Chebyshev' is not defined
:
from numpy.polynomial.chebyshev import Chebyshev
from Demo_func import chebyshev_nodes
chebyshev_nodes(5, [1,5])
它产生这个错误下面,那么它工作得很好。
from numpy.polynomial.chebyshev import Chebyshev
def chebyshev_nodes(degree, domain):
return Chebyshev.basis(degree,domain).roots()
chebyshev_nodes(5, [1,5])
我的理解是,进口的切比雪夫是全球性的。但不知何故,它在我的模块Demo_func中运行。我如何编写一个依赖于Chebyshev类的模块?
“我的理解是,进口切比雪夫是全球性的” - 事实并非如此。它执行的模块初始化是全局性的,但它只会使'Chebyshev'名称可用于执行导入的范围。 – user2357112
谢谢,这很有帮助。在函数定义中导入Chebyshev。这是做到这一点的正确方法吗? –