【问题标题】:python import function from file - global name '' is not definedpython从文件导入函数-未定义全局名称''
【发布时间】:2018-05-10 08:49:31
【问题描述】:

我在从文件中导入一个函数并在另一个函数中执行它时遇到问题。我无法将变量 'efgh' 传递给 fun_a()。

#cat fun_a.py 
def fun_a(abcd):
    print '%s - %s'%(abcd, efgh)
if __name__ == "__main__":
    pass

#python
Python 2.7.5 (default, Oct 11 2015, 17:47:16) [GCC 4.8.3 20140911 (Red Hat 
4.8.3-9)] on linux2 Type "help", "copyright", "credits" or "license" for 
more information.
>>> from fun_a import *
>>> efgh = 'test2'
>>> fun_a('test1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "fun_a.py", line 2, in fun_a
    print '%s - %s'%(abcd, efgh)
NameError: global name 'efgh' is not defined

我希望结果是“test1 - test2”。

【问题讨论】:

    标签: python function file import


    【解决方案1】:

    声明global efgh然后使用它

    例如:

    global efgh
    efgh = 'test2'
    def fun_a(abcd):
        print '%s - %s'%(abcd, efgh)
    
    fun_a('test1')
    

    【讨论】:

      【解决方案2】:

      这不可能。 Python 中的global 表示“在单个模块内”;没有办法[*] 在 shell 中定义一个会影响导入脚本的全局变量。

      您应该将efgh 作为函数的参数。

      [*] 好吧,你可以打猴子补丁,但不要那样做。

      【讨论】:

        猜你喜欢
        • 2013-04-27
        • 2017-06-07
        • 2019-10-29
        • 2017-02-03
        • 2013-08-23
        • 2013-11-12
        • 2014-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多