【发布时间】:2017-07-17 15:53:12
【问题描述】:
我是 Python 新手,如果我在写这个问题时没有使用正确的语言,我深表歉意。我在 Windows 机器上使用 Python 3.6.1。我提供了一个我遇到的问题的工作示例。
假设我编写了一个保存在文件 Demo_func.py 中的模块。它包含以下功能:
def chebyshev_nodes(degree, domain):
return Chebyshev.basis(degree,domain).roots()
然后我运行以下脚本:
from numpy.polynomial.chebyshev import Chebyshev
from Demo_func import chebyshev_nodes
chebyshev_nodes(5, [1,5])
它会产生这个错误:
NameError: 名称“Chebyshev”未定义
如果我改为在我的脚本中编写函数 chebyshev_nodes,如下所示,那么它工作得很好。
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 是全球性的” - 它不是。它执行的模块初始化是全局的,但它只使
Chebyshev名称可用于执行导入的作用域。 -
谢谢,这很有帮助。在函数定义中导入 Chebyshev 是可行的。这是正确的方法吗?
标签: python class import module