【问题标题】:Ipython notebook : Name error for Imported script functionIpython 笔记本:导入脚本函数的名称错误
【发布时间】:2014-07-16 10:23:29
【问题描述】:

我有两个脚本sources.pynest.py。它们是这样的

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

当我像python sources.py 这样运行脚本时,它工作正常。

但是在 Ipython notebook 环境中如果我执行以下操作

In [1]: from sources import *

In [2]: detect()

我收到以下错误

---------------------------------------------------------------------------
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

我对为什么会发生这种情况感到困惑。你能告诉我这两种情况有什么不同以及如何解决这个问题吗?

【问题讨论】:

  • '_init_' != '__init__'。您有两个循环的文件 importing 彼此。您实际运行的代码在哪里?请提供一个minimal example,该minimal example确实有效并复制了该问题。为什么不将它们组合成一个脚本?
  • @jonrsharpe 谢谢,我会试试的。抱歉不清楚。

标签: python ipython ipython-notebook nameerror


【解决方案1】:

事情是有区别的

import something

from something import *

关于命名空间。

如果你有递归导入,最好不要“从某物导入*”或“将某物作为其他东西导入”

你在这里得到一个完整的解释:

Circular (or cyclic) imports in Python

【讨论】:

    猜你喜欢
    • 2015-05-12
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2014-04-13
    • 2017-01-14
    • 2013-05-27
    • 2016-09-25
    相关资源
    最近更新 更多