首页 > 解决方案 > 有条件地调用另一个脚本中的函数并使用它的变量

问题描述

我有两个脚本,一个在 Python 27 中调用另一个。第一个脚本 Script1.py 包含一些条件语句。然后我有第二个脚本 Script2.py,它调用第一个脚本并将参数传递给从第一个脚本导入的函数 func1。

但是,当我运行第二个脚本时,我得到一个错误,即未定义 func1 中的变量。为什么是这样?我该怎么做才能解决?

谢谢

脚本1.py:

def func1(var):

    if var == '1':

        test1 = 'a'
        test2 = 'b'
        test3 = 'c'

    if var == '2':

        test1 = 'd'
        test2 = 'e'
        test3 = 'f'

脚本2.py:

from Script1 import func1

func1('1')

print test1, test2, test3

func1('2')

print test1, test2, test3


Traceback (most recent call last):
  File "G:/Python27/Script2.py", line 5, in <module>
    print test1, test2, test3
NameError: name 'test1' is not defined

标签: pythonpython-2.7

解决方案


def func1(var):

    if var == '1':
        test1 = 'a'
        test2 = 'b'
        test3 = 'c'

    elif var == '2':
        test1 = 'd'
        test2 = 'e'
        test3 = 'f'

    # to catch error when different argument is passed
    else:
        test1 = test2 = test3 = None

    return test1, test2, test3 # return the variables, so they can be used outside

和:

from Script1 import func1

test1, test2, test3 = func1('1')

print test1, test2, test3

test1, test2, test3 = func1('2')

print test1, test2, test3

推荐阅读