Ipython notebook:导入的脚本函数的名称错误 [英] Ipython notebook : Name error for Imported script function
问题描述
我有两个脚本 sources.py
和 nest.py
。他们是这样的
sources.py
import numpy as来自nest import的np
*
def make_source():
#rest代码
def detect():
Nest = nest()
Nest.fit()
if __name __ =='main':
detect()
nest.py
从np
导入numpy sources import *
class nest(object):
def _init_(self):
self.source = make_source()
def fit(self):
#rest代码
当我运行脚本时 python sources.py
一切正常。
但是在Ipython笔记本环境中,如果我执行以下操作
在[1]中:从来源导入*
在[2]中:detect()
我收到以下错误
---------------- -------------------------------------------------- ---------
NameError Traceback(最近一次调用最后一次)
< ipython-input-5-e9c378341590> in< module>()
----> detect()
C:\sources.pyc in detect()
- > 7 Nest = nest()
C:\\\
est.pyc in _init_()
- > 7 self.source = make_source()
NameError:全局名称'make_source'未定义
我很困惑为什么会这样。你能否告诉我这两种情况有何不同以及如何解决这个问题?
事情是
<$ p $之间存在差异p>
导入一些东西
和
来自导入*
有关名称空间的信息。
如果您有递归导入,最好不要从导入内容*或导入某些东西
你在这里得到一个完整的解释:
I have two scripts sources.py
and nest.py
. They are something like this
sources.py
import numpy as np
from nest import *
def make_source():
#rest of the code
def detect():
Nest = nest()
Nest.fit()
if __name__=='main':
detect()
nest.py
import numpy as np
from sources import *
class nest(object):
def _init_(self):
self.source = make_source()
def fit(self):
#rest of the code
When I run the script like python sources.py
It works fine.
But in the Ipython notebook environment if I do the following
In [1]: from sources import *
In [2]: detect()
I am getting the following error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-e9c378341590> in <module>()
----> detect()
C:\sources.pyc in detect()
--> 7 Nest = nest()
C:\nest.pyc in _init_()
--> 7 self.source = make_source()
NameError: global name 'make_source' is not defined
I am confused about why this is occurring. Can you give me an insight on how it is different in both cases and how to solve this ?
The thing is that there is a difference between
import something
and
from something import *
concerning namespaces.
If you have recursive imports its better to never do "from something import *" or "import something as someotherthing"
You get a full explanation here:
Circular (or cyclic) imports in Python
这篇关于Ipython notebook:导入的脚本函数的名称错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!