Python 函数 Return 键入另一个脚本的参数
Python Function Return Type as Param to Another Script
我有一个带有函数定义 (func) 的脚本 (module.py)。我能够使用导入模块和 module.a 实用程序从另一个脚本 (script.py) 获取局部变量 (a)。
但是有没有办法在函数 (func) 中检索 return 类型或局部变量 (b, n) 并将其传递给调用脚本 (script.py)。
# Script Name: module.py
a = 10 # Module Script Local Variable
def func( n ):
print(n + 20)
b = 20 # Module Script Function Local Var.
return n, b
print(a) # Gives 10
print(n, b) # NameError: name 'n'/'b' is not defined
调用脚本:
# Main Script Name: script.py
import module # Or from module import a, func
a_new = module.a # Gives 10
module.func(5) # Function Call
n_new = module.n # AttributeError: module 'module' has no attribute 'n'
b_new = module.b # AttributeError: module 'module' has no attribute 'b'
您的 module.py
将在导入时执行一次 print
调用。这可能不是你想要的。
关于 n
和 b
:这些是 module.func
的本地内容,在此函数之外不可用。
试试这个:
n_new, b_new = module.func(5)
我有一个带有函数定义 (func) 的脚本 (module.py)。我能够使用导入模块和 module.a 实用程序从另一个脚本 (script.py) 获取局部变量 (a)。
但是有没有办法在函数 (func) 中检索 return 类型或局部变量 (b, n) 并将其传递给调用脚本 (script.py)。
# Script Name: module.py
a = 10 # Module Script Local Variable
def func( n ):
print(n + 20)
b = 20 # Module Script Function Local Var.
return n, b
print(a) # Gives 10
print(n, b) # NameError: name 'n'/'b' is not defined
调用脚本:
# Main Script Name: script.py
import module # Or from module import a, func
a_new = module.a # Gives 10
module.func(5) # Function Call
n_new = module.n # AttributeError: module 'module' has no attribute 'n'
b_new = module.b # AttributeError: module 'module' has no attribute 'b'
您的 module.py
将在导入时执行一次 print
调用。这可能不是你想要的。
关于 n
和 b
:这些是 module.func
的本地内容,在此函数之外不可用。
试试这个:
n_new, b_new = module.func(5)